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

2024-10-01 07:50:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个tkinterFrame,我试图通过它们传递值来确定按下了哪个按钮。以下是我所拥有的:


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':
             ....

当我尝试比较从MainFrame类的get_button_text()函数得到的结果时,它返回空值,即使该函数内的print语句打印我传递给button_controller()函数的文本。我不明白这里发生了什么


Tags: textselfgetframesinitdefbuttonframe
1条回答
网友
1楼 · 发布于 2024-10-01 07:50:30

您应该首先更新self.button_text,然后切换页面:

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

相关问题 更多 >