WxPython, trying to remove all buttons from sizer, always leaves one remaining

I have the following code to add 6 buttons to BoxSizer

for word in words: btn = wx.Button(self, label=word) btn.Bind(wx.EVT_BUTTON, self.onWordSelect) 

In my onWordSelect method onWordSelect I try to remove all the buttons that I created in Sizer so that I can create new buttons. My problem is that all buttons are deleted, except the last one.

Here is my code for removing buttons:

 for child in self.sizer.GetChildren(): self.sizer.Remove(child.Window) self.sizer.Layout() 

When checking len(self.sizer.GetChildren()) it returns 0 , but the last button is still displayed on the screen.

+6
source share
4 answers

From http://wxpython.org/docs/api/wx.Sizer-class.html#Remove :

For historical reasons, calling this method with the wx.Window parameter is depressing since it will not be able to destroy the window because it belongs to its parent. You should use Detach instead.

You have deleted elements from sizer, but they still exist, printed one above the other: add one line to your loop in destroy or hide , and that should be fine.

+4
source

After a little study of the documentation, I found that the easiest way to delete all controls is to use self.sizer.DeleteWindows() instead of deleting each button individually in a loop.

+3
source

In addition to responding to cramer, an example of a log switch. Thanks Cramer!

 def onToggleLog(self, e): self.showlog = not self.showlog if self.showlog: self.sizer.Add(self.log, 1, wx.EXPAND) self.log.Show() else: self.sizer.Detach(self.log) self.log.Hide() self.sizer.Layout() 
0
source

For clarity, cramer-destroy comment, here is how I solved the problem I had:

 class myFrame(wx.Frame): def__init__(self, title): #make the FlexGridSizer specifying only the columns, not the rows #make a panel #create widgets with the panel as the parent #add widgets to the sizer self.addLastRow() #set the sizer, call layout, etc... def addLastRow(self): lastBtn = wx.Button(self.myScrolledPanel, -1,"Add New Row", style=wx.BU_EXACTFIT) numBlanks = self.numTotalColumns-1 for i in range(numBlanks): self.myFlexGridSizer.AddF(wx.StaticText(self.myScrolledPanel, -1, ''), wx.SizerFlags(0)) self.myFlexGridSizer.AddF(lastBtn, wx.SizerFlags(0)) self.Bind(wx.EVT_BUTTON, self.AddNewRowElements, addButton) def removeLastRow(self): myFlexGridItems = self.myFlexGridSizer.GetChildren() for i in range(self.numTotalColumns): myFlexGridItems[len(myFlexGridItems)-1].GetWindow().Destroy() def AddNewRowElements(self, event): self.removeLastRow() #add elements self.addLastRow() self.myFlexGridSizer.Layout() 
0
source

All Articles