【问题标题】:How do I use the tkinter variable in my code?如何在我的代码中使用 tkinter 变量?
【发布时间】: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() 函数来获取字符串。

标签: python tkinter


【解决方案1】:

您需要将变量与标签链接。相反,您尝试将变量本身设置为标签的文本。

替换这个:

self.label = tk.Label(self, text=self.label_text)

...用这个:

self.label = tk.Label(self, textvariable=self.label_text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 2023-03-27
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多