简体   繁体   English

Tkinter - 在不同的类中设置共享变量和访问

[英]Tkinter - Set Shared Variable and Access in Different Class

I have created my own python script following the suggestion of this post, Switch between two frames in tkinter .我按照这篇文章的建议创建了自己的 python 脚本, 在 tkinter 中的两帧之间切换

I have also followed this post, How to access variables from different classes in tkinter python 3 .我也关注了这篇文章, How to access variables from different classes in tkinter python 3

However, I want to set or change the value of the shared value in one frame and then access it in another, when I switch between the frames.但是,当我在帧之间切换时,我想在一个帧中设置或更改共享值的值,然后在另一个帧中访问它。

class MainApplication(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.app = {
            "foo": None
        }

        self.frames = {}

        for F in (PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("PageOne")

    def show_frame(self, page_name, **kwargs):
        # self.app["foo"] = kwargs.get("bar")
        frame = self.frames[page_name]
        frame.tkraise()

class PageOne(tk.Frame):

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

        button = tk.Button(self, text="Login", command=lambda: self.func())
        button.pack()

    def func(self):
        # self.controller.show_frame("PageTwo", bar="something")
        self.controller.show_frame("PageTwo")

class PageTwo(tk.Frame):

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

        print(self.controller.app["foo"])

I tried adding arguments to the show_frame() function that allows for switching between frames but the result in PageTwo is still None.我尝试向 show_frame() 函数添加参数,该函数允许在帧之间切换,但 PageTwo 中的结果仍然是 None。 I have commented out the lines, to show what I attempted.我已经注释掉了这些行,以显示我的尝试。

It's important to understand that PageTwo.__init__ runs at the very start of the program, before the user has a chance to do anything.重要的是要了解PageTwo.__init__在程序的最开始运行,在用户有机会做任何事情之前。 If you want to access app after switching, you're going to have to add code that runs after switching.如果要在切换后访问app ,则必须添加在切换后运行的代码。

The following answer, linked to from where you copied your code, shows you one way to do that:以下答案链接到您复制代码的位置,向您展示了一种方法:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM