Calling functions from a Tkinter Frame to another

To call a method on another object, you need a reference to the object. The code you copied for managing the different pages is designed to make this easy, but it is missing a function to get the instance of a page.

So, the first think you need to do is add a get_page method on the controller:

class Myapp(tk.Tk):
    ...
    def get_page(self, page_class):
        return self.frames[page_class]

With that, you can get the page instance, and with the page instance you can call the method.

Next, you need to keep a reference to the controller so that you can call it from other functions:

class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        ...

Finally, you can now use the controller to get the page, and with the page you can call the function.

My recommendation is to not use lambda unless you absolutely need it, and in this case you do not. It’s much easier to write and debug your code when you use proper functions instead of lambda.

For example:

class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        ...
        button2 = ttk.Button(..., command=self.do_button)
        ...

    def do_button(self):
        page = self.controller.get_page(PageOne)
        page.function()

Leave a Comment