Python 3.x 更新标签上的文本
我正在学习关于tkinter的Oreilly教程,但是教程中提供的代码对我不适用。“选择一个”消息不会显示,而是显示:Python 3.x 更新标签上的文本,python-3.x,tkinter,tkinter-label,Python 3.x,Tkinter,Tkinter Label,我正在学习关于tkinter的Oreilly教程,但是教程中提供的代码对我不适用。“选择一个”消息不会显示,而是显示:PY\u VAR0。当我点击hello按钮时,什么也没发生。单击“再见”按钮时,窗口将按预期关闭,但不会显示任何消息 值得注意的是,在我之前: def say_hello(self): self.label.configure(text="Hello World!") def say_goodbye(self): self.label.configu
PY\u VAR0
。当我点击hello按钮时,什么也没发生。单击“再见”按钮时,窗口将按预期关闭,但不会显示任何消息
值得注意的是,在我之前:
def say_hello(self):
self.label.configure(text="Hello World!")
def say_goodbye(self):
self.label.configure(text="Goodbye! \n (Closing in 2 seconds)")
self.after(2000, self.destroy)
并收到属性错误:attributeerror:“\u tkinter.tkapp”对象没有属性“label”站点:stackoverflow.com
我不确定哪里不对,因为我在这两种情况下都明确地遵循了这个例子
我的代码如下:
import tkinter as tk
class Window(tk.Tk):
def __init__(self):
super().__init__()
self.title('Hello Tkinter')
self.label_text = tk.StringVar()
self.label_text.set("Choose One")
label = tk.Label(self, text=self.label_text)
label.pack(fill=tk.BOTH, expand=1, padx=100, pady=30)
hello_button = tk.Button(self, text='Say Hello',
command=self.say_hello)
hello_button.pack(side=tk.LEFT, padx=(20, 0), pady=(0, 20))
goodbye_button = tk.Button(self, text ='Say Goodbye',
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 World!")
def say_goodbye(self):
self.label_text.set("Goodbye! \n (Closing in 2 seconds)")
self.after(2000, self.destroy)
if __name__ == "__main__":
window = Window()
window.mainloop()
您需要设置标签
textvariable=self.label\u text
,而不是text=self.label\u text
import tkinter as tk
class Window(tk.Tk):
def __init__(self):
super().__init__()
self.title('Hello Tkinter')
self.label_text = tk.StringVar()
self.label_text.set("Choose One")
label = tk.Label(self, textvariable=self.label_text)
label.pack(fill=tk.BOTH, expand=1, padx=100, pady=30)
hello_button = tk.Button(self, text='Say Hello',
command=self.say_hello)
hello_button.pack(side=tk.LEFT, padx=(20, 0), pady=(0, 20))
goodbye_button = tk.Button(self, text ='Say Goodbye',
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 World!")
def say_goodbye(self):
self.label_text.set("Goodbye! \n (Closing in 2 seconds)")
self.after(2000, self.destroy)
if __name__ == "__main__":
window = Window()
window.mainloop()
在本网站上搜索“PY_VAR0”。你会发现很多类似的问题。至于“无属性‘标签’”,这是在告诉你真相。如果您没有得到预期的输出,请参考这些,并请发表评论