【问题标题】:Is there a way to dynamically change the widgets displayed using Tkinter?有没有办法动态更改使用 Tkinter 显示的小部件?
【发布时间】:2020-06-01 12:06:45
【问题描述】:

我正在使用 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()

除了上面的,我也试过了:

  • 更新主循环内的应用实例,即在实例化app = App()之后
  • 将 show_label 设为类变量,将 change() 设为类方法

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

谢谢

【问题讨论】:

  • __init__ 函数仅在您的应用程序上调用一次。窗口中的小部件集是可变的,但您必须在其他地方执行此操作。另见stackoverflow.com/q/3819354/1256452

标签: python tkinter dynamic widget


【解决方案1】:

您所犯的错误似乎是认为__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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2023-03-30
    • 2011-04-20
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多