2

我正在阅读关于 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()

4

1 回答 1

2

您需要设置标签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()
于 2020-10-28T05:50:23.510 回答