24

I am writing a GUI-based program using Python's tkinter library. I am facing a problem: I need to delete all children elements (without deleting a parent element, which in my case is colorsFrame).

My code:

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)

How do I achieve this?

nbro
  • 15,395
  • 32
  • 113
  • 196
Roman Nazarkin
  • 2,209
  • 5
  • 23
  • 44

1 Answers1

44

You can use winfo_children to get a list of all children of a particular widget, which you can then iterate over:

for child in infoFrame.winfo_children():
    child.destroy()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • 1
    Yes! This is works! But new problem appeared: size of `infoFrame` block remains the same as with children blocks before deleting. Know how to solve the problem? – Roman Nazarkin Apr 14 '13 at 05:03
  • 2
    @RomanNazarkin: the short answer is this: when you destroy all the children widgets, pack no longer thinks it "owns" the window since there are no children to manage. Because of that, it doesn't try to resize the window. A simple work-around is to pack a tiny 1x1 frame in the window temporarily, to cause pack to resize the containing frame. – Bryan Oakley Apr 14 '13 at 13:20
  • 1
    @BryanOakley: For me this method seems not to work, or rather seems to corrupt the frame. Afterwards I get an error, when trying to add widgets to it again like this: `widget.grid(in_=self.frame, sticky=sticky, row=0, column=0)` The error is the following: `_tkinter.TclError: bad window path name ` Do you know how to fix it? – Zelphir Kaltstahl Aug 09 '15 at 18:11
  • 1
    Nevermind, I found the mistake I made. This method works. Just be sure not to create a widget and settings its master to the frame you want to clear, before you clear that frame. Otherwise you'll destroy the widget as well and it will not be addable to the frame. – Zelphir Kaltstahl Aug 10 '15 at 09:44