有没有办法动态更改使用 Tkinter 显示的小部件?

Is there a way to dynamically change the widgets displayed using Tkinter?

我正在使用 Tkinter 构建一个 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()

除了上面的,我也试过:

非常感谢对此事的任何帮助!

谢谢

看来您犯的错误是认为 __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()