简体   繁体   English

Tkinter:如何将 StringVar 传递给另一个 class?

[英]Tkinter: How to pass a StringVar to another class?

I have two tkinter Frame s through which I'm trying to pass values to determine which button was pressed.我有两个 tkinter Frame ,我试图通过它们传递值以确定按下了哪个按钮。 Here is what I have:这是我所拥有的:


class GUIHandler(tk.Tk):

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

        self.frames = {}

        for F in (MainFrame, GraphsTask):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(MainFrame)

class MainFrame(tk.Frame):

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

        tk.Button(self, text="Task 2a", 
                  command=lambda: self.button_controller(GraphsTask, 'task_2a'))

    def button_controller(self, class_name, btn_text):
        self.controller.show_frame(class_name)
        self.button_text.set(btn_text)

    def get_button_text(self):
        print(self.button_text.get())
        return self.button_text.get()

class GraphsTask(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.bind("<<Show>>", self.get_graph)

    def get_graph(self, event):
        if self.controller.frames[MainFrame].get_button_text() == 'task_2a':
             ....

When I try to compare the result I get from get_button_text() function from MainFrame class, it returns empty even though the print statement inside that function prints the text I passed onto button_controller() function. When I try to compare the result I get from get_button_text() function from MainFrame class, it returns empty even though the print statement inside that function prints the text I passed onto button_controller() function. I do not understand what is going on here.我不明白这里发生了什么。

You should update self.button_text first and then switch page:您应该先更新self.button_text然后切换页面:

    def button_controller(self, class_name, btn_text):
        self.button_text.set(btn_text)
        self.controller.show_frame(class_name)

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

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