【发布时间】:2022-01-13 10:28:42
【问题描述】:
我正在练习如何使用 Tkinter 制作 GUI,但是我不确定如何修复此代码,非常感谢任何帮助。我希望标签随着按钮输入而改变,但它甚至根本不显示。标签的唯一输出是 PY_VAR0
class Window(tk.Tk):
def __init__(self):
super().__init__()
self.title("My Window")
self.label_text = tk.StringVar()
self.label_text.set("Choose One:")
self.label = tk.Label(self, text=self.label_text)
self.label.pack(fill=tk.BOTH, expand=1, padx=150, pady=30)
hello_button = tk.Button(self, text="Say Hello",bg='black',fg='white',
command=self.say_hello)
hello_button.pack(side=tk.LEFT, padx=(20,0), pady=(0,20))
goodbye_button = tk.Button(self, text="Say Goodbye",bg='black',fg='white',
command=self.say_goodbye)
goodbye_button.pack(side=tk.RIGHT, padx=(0,20), pady=(0,20))
def say_hello(self):
self.label_text.set("Hello there!")
def say_goodbye(self):
self.label_text.set("See you next time!\n(Closing in 2 seconds)")
self.after(2000, self.destroy)
if __name__ == "__main__":
window=Window()
window.mainloop()
【问题讨论】:
-
创建标签时,您应该将 StringVar
self.label_text传递为textvariable而不是text。当您将其作为text传递时,对象将被转换为字符串,str(tk.StringVar())将产生"PY_VARx"。将其作为textvariable传递告诉 tkinter 使用对象上的get()函数来获取字符串。