[英]Tkinter: How to pass a StringVar to another class?
我有兩個 tkinter Frame
,我試圖通過它們傳遞值以確定按下了哪個按鈕。 這是我所擁有的:
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. 我不明白這里發生了什么。
您應該先更新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.