簡體   English   中英

Tkinter - 在不同的類中設置共享變量和訪問

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

我按照這篇文章的建議創建了自己的 python 腳本, 在 tkinter 中的兩幀之間切換

我也關注了這篇文章, How to access variables from different classes in tkinter python 3

但是,當我在幀之間切換時,我想在一個幀中設置或更改共享值的值,然后在另一個幀中訪問它。

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"])

我嘗試向 show_frame() 函數添加參數,該函數允許在幀之間切換,但 PageTwo 中的結果仍然是 None。 我已經注釋掉了這些行,以顯示我的嘗試。

重要的是要了解PageTwo.__init__在程序的最開始運行,在用戶有機會做任何事情之前。 如果要在切換后訪問app ,則必須添加在切換后運行的代碼。

以下答案鏈接到您復制代碼的位置,向您展示了一種方法:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM