如果您要添加和删除小部件,我会学习sizer。如果您要添加一行小部件,则将所有这些小部件放在它们自己的尺寸器中。这是添加小部件行的示例:
import wx
########################################################################
class MyPanel(wx.Panel):
""""""
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent)
self.id = 1
self.row_dict = {}
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
addBtn = wx.Button(self, label="Add")
addBtn.Bind(wx.EVT_BUTTON, self.onAdd)
self.mainSizer.Add(addBtn, 0, wx.ALL|wx.CENTER, 5)
self.SetSizer(self.mainSizer)
#----------------------------------------------------------------------
def onAdd(self, event):
"""
Add row of widgets
"""
sizer = wx.BoxSizer(wx.HORIZONTAL)
label = wx.StaticText(self, label="Test")
removeBtn = wx.Button(self, label="Remove row", name=str(self.id))
removeBtn.Bind(wx.EVT_BUTTON, self.onRemove)
self.row_dict[str(self.id)] = sizer
self.id += 1
sizer.Add(label, 0, wx.ALL, 5)
sizer.Add(removeBtn, 0, wx.ALL, 5)
self.mainSizer.Add(sizer)
self.mainSizer.Layout()
#----------------------------------------------------------------------
def onRemove(self, event):
"""
Remove row
"""
btn = event.GetEventObject()
name = btn.GetName()
print name
print "removing => ", self.row_dict[name]
sizer = self.row_dict[name]
for child in sizer.GetChildren():
widget = child.GetWindow()
print widget
sizer.Remove(widget)
#self.mainSizer.Remove(self.row_dict[name])
self.mainSizer.Layout()
self.Layout()
########################################################################
class MyFrame(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title="Add Widgets")
panel = MyPanel(self)
self.Show()
if __name__ == "__main__":
app = wx.App(False)
frame = MyFrame()
app.MainLoop()
我无法让 remove 方法正常工作,但 add 方法效果很好。希望这至少可以帮助您入门。