有没有一种方法可以动态更改使用Tkinter显示的窗口小部件?

时间:2020-06-01 12:06:45

标签: python tkinter dynamic widget

我正在用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()
  • 使show_label为类变量,使change()为类方法

对此事的任何帮助,我们将不胜感激!

谢谢

1 个答案:

答案 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()