【问题标题】:How to delete all children elements?如何删除所有子元素?
【发布时间】:2013-04-06 10:08:21
【问题描述】:

我正在使用 Python 的 tkinter 库编写一个基于 GUI 的程序。我面临一个问题:我需要删除 all 子元素(不删除父元素,在我的例子中是 colorsFrame)。

我的代码:

infoFrame = Frame(toolsFrame, height = 50, bd = 5, bg = 'white')
colorsFrame = Frame(toolsFrame)

# adding some elements

infoFrame.pack(side = 'top', fill = 'both')
colorsFrame.pack(side = 'top', fill = 'both')

# set the clear button
Button(buttonsFrame, text = "Clear area",
               command = self.clearArea).place(x = 280, y = 10, height = 30)

我如何做到这一点?

【问题讨论】:

    标签: python user-interface tkinter


    【解决方案1】:

    您可以使用winfo_children 获取特定小部件的所有子组件的列表,然后您可以对其进行迭代:

    for child in infoFrame.winfo_children():
        child.destroy()
    

    【讨论】:

    • 是的!这是作品!但出现了新问题:infoFrame 块的大小与删除前的子块相同。知道如何解决问题?
    • @RomanNazarkin:简短的回答是:当您销毁所有子小部件时,pack 不再认为它“拥有”窗口,因为没有要管理的子窗口。因此,它不会尝试调整窗口大小。一个简单的解决方法是在窗口中临时打包一个微小的 1x1 框架,以使 pack 调整包含框架的大小。
    • @BryanOakley:对我来说,这种方法似乎不起作用,或者说似乎破坏了框架。之后我收到一个错误,当我尝试再次向它添加小部件时:widget.grid(in_=self.frame, sticky=sticky, row=0, column=0) 错误如下:_tkinter.TclError: bad window path name <random cryptic numbers here> 你知道如何解决它吗?
    • 没关系,我发现了我犯的错误。这种方法有效。在清除该框架之前,请确保不要创建小部件并将其主人设置为您要清除的框架。否则,您也会破坏小部件,并且无法将其添加到框架中。
    猜你喜欢
    • 2014-05-04
    • 2011-01-03
    • 1970-01-01
    • 2012-09-01
    • 2021-12-04
    • 2017-01-22
    • 2014-11-18
    • 1970-01-01
    • 2020-05-01
    相关资源
    最近更新 更多