【问题标题】:Updating text on a label更新标签上的文本
【发布时间】:2020-10-28 04:54:37
【问题描述】:

我正在阅读关于 tkinter 的 Oreilly 教程,但教程中提供的代码对我不起作用。 “选择一个”消息不显示,而是显示:PY_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: '_tkinter.tkapp' object has no attribute 'label' site: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()

【问题讨论】:

标签: python-3.x tkinter tkinter-label


【解决方案1】:

你需要设置标签textvariable=self.label_text而不是text=self.label_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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 2023-03-09
    • 2011-08-06
    • 1970-01-01
    相关资源
    最近更新 更多