繁体   English   中英

销毁动态创建的小部件

[英]Destroying a dynamically created widget

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

Tkinter:如何动态创建可以销毁或删除的小部件?

可接受的答案是:

您需要将动态创建的窗口小部件存储在列表中。 有类似的东西

  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不知道它们是在他们的列表中排名第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())

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

如果要保存对窗口小部件的引用,则必须在将窗口小部件放置到窗口中的另一步骤中创建窗口小部件。

更好的解决方案是利用类和对象。 创建您自己的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)

使用enumerate()函数将索引传递到命令函数

def editAanstuur():
    openfiles = filedialog.askopenfilenames()
    if not openfiles:
        return 
    for i, file in enumerate(openfiles):
        newtop = Toplevel(nGui, height=100, width=100)
        labelTitle = Label(newtop, text=file).pack()
        newButton = Button(newtop, text="Save", command=lambda index=i: print(index)).pack()
        aanstuur_files.append(file)
        aanstuur_buttons.append(newButton)
        aanstuur_frames.append(newtop)

确保在定义lambda时将索引作为关键字参数传递给绑定值(闭包将使用i的最后一个值)。

enumerate()使用第二个参数,即索引起始处,默认为0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM