Calling functions from a Tkinter Frame to another

痴心易碎 提交于 2019-11-27 05:23:26

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()

You could consider saving references to you GUI fields you need to update in, for example, a dict in your MyApp class. That way you can access them from anywhere in the class regardless of where the actual GUI element happens to be placed.

GUI programming usually produces quite messy classes, using a dict to keep track of the elements reduces the mess. Others like to keep separate class attributes for each element you need to access later.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!