我正在用Tkinter构建一个GUI,在该GUI中,我想为用户提供通过单击按钮将输入小部件更改为标签小部件(反之亦然)的选项。
我尝试了几种不同的方法,但无法使其正常工作。这是我尝试解决此问题的方法之一:
import tkinter as tk
show_label = False
class App(tk.Tk):
def __init__(self):
super().__init__()
label = tk.Label(self, text="This is a label")
entry = tk.Entry(self)
button = tk.Button(self, text="Label/Entry",
command=self.change)
if show_label:
label.pack()
else:
entry.pack()
button.pack()
def change(self):
global show_label
show_label = not show_label
self.update()
if __name__ == '__main__':
app = App()
app.mainloop()
除上述内容外,我还尝试过:
app = App()
后对此事的任何帮助,我们将不胜感激!
谢谢
答案 0 :(得分:2)
您所犯的错误似乎是认为__init__
中的代码多次运行。创建App
的实例时,它仅运行一次。
要修复代码,请在单击按钮时将用于显示条目或标签的逻辑移到运行的代码中。另外,您需要使用实例变量来保存对小部件的引用,以便可以在其他函数中对其进行引用。
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.label = tk.Label(self, text="This is a label")
self.entry = tk.Entry(self)
self.button = tk.Button(self, text="Label/Entry",
command=self.change)
self.button.pack()
self.show_label = False
def change(self):
self.show_label = not self.show_label
if self.show_label:
self.entry.pack_forget()
self.label.pack()
else:
self.label.pack_forget()
self.entry.pack()
if __name__ == '__main__':
app = App()
app.mainloop()