python - 销毁动态创建的小部件

标签 python tkinter python-3.3

我基本上有一个类似的问题,尽管我认为它没有得到正确的回答:

Tkinter: How can I dynamically create a widget that can then be destroyed or removed?

accepted answer是:

You'll want to store the dynamically-created widgets in a list. Have something like

     dynamic_buttons = []

     def onDoubleClick(event):
     ...
     button = Button(...)
     dynamic_buttons.append(button)
     button.pack() 

You can then access the buttons for removal with, say,

     dynamic_buttons[0].destroy()

你可以看到他们所说的引用不是变量,这里使用数字0。但是,当动态创建小部件时,如何将这些引用连接到按钮?

假设您创建了一个顶级小部件(显示文件的内容),并且希望有一个按钮来关闭该小部件。动态创建将允许打开多个文件。 问题是,即使有了这个列表,按钮如何“知道”它属于哪个小部件,因为没有硬引用(很好,您有一个项目列表,但顶级 5 + 按钮 5 不知道它们是在他们的名单中排名第五)。按钮和顶层始终只有一个“事件”版本,并且可以将其删除。

aanstuur_files = []
aanstuur_frames = []
aanstuur_buttons = []

def editAanstuur():
    openfiles = filedialog.askopenfilenames()
    if not openfiles:
        return 
    for file in openfiles:
        newtop = Toplevel(nGui, height=100, width=100)
        labelTitle = Label(newtop, text=file).pack()
        newButton = Button(newtop, text="save & close", command= ...).pack()
        aanstuur_files.append(file)
        aanstuur_buttons.append(newButton)
        aanstuur_frames.append(newtop)

最佳答案

按钮如何知道它属于哪个窗口?你告诉它:

newButton = Button(newtop, command=lambda top=newtop: top.destroy())

顺便说一句,您在代码中将 None 分配给 newButton。这是因为您正在执行 newbutton = Button(...).pack(),这意味着 newbutton 获取 pack() 的值始终为“无”。

如果您要保存对小部件的引用,则必须在将其放置在窗口中时的单独步骤中创建该小部件。

更好的解决方案是利用类和对象。创建您自己的 Toplevel 子类,该实例将为您跟踪所有子小部件。例如:

class MyToplevel(Toplevel):
    def __init__(self, parent, filename, *args, **kwargs):
        Toplevel.__init__(self, parent, *args, **kwargs)
        self.filename = filename
        self.savebutton = Button(..., command=self.save)
        ...
    def save(self):
        print "saving...", self.filename
        ...
        self.destroy()
...
openfiles = filedialog.askopenfilenames()
if not openfiles:
    return 
for file in openfiles:
    newtop = MyToplevel(nGui, file, height=100, width=100)

关于python - 销毁动态创建的小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17512297/

相关文章:

python - 验证使用 ElementTree 解析的 XML,可能吗?

Python Tkinter : Bind function to list of variables in a for-loop

python - Bash 别名 --> Python 2.7 到 Python 3.3

python - Python 中的路径搜索

Python: "import posix"问题

python - 如何在 Tkinter 中找出 PhotoImage 的大小?

python - 在多个 Tkinter LabelFrames 之间使用网格对齐小部件

python - 为什么要分发和 pip 安装到我的 virtualenv 的 ./local/bin?

python - 使用 Python 写入 CSV 会添加空行

python - 如何让两个脚本引用同一个模块