让按钮排序有点棘手,但关键是找到要排序的东西。您可以使用按钮标签或按钮名称。我选择了后者。以下代码还演示了如何显示/隐藏按钮:
import random
import wx
########################################################################
class MyPanel(wx.Panel):
""""""
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent)
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
hSizer = wx.BoxSizer(wx.HORIZONTAL)
for item in range(10):
val = random.choice(range(10000,99999))
label = "Button %s" % val
name = "btn%s" % val
btn = wx.Button(self, label=label, name=name)
self.mainSizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)
toggleBtn = wx.Button(self, label="Hide/Show Some Buttons")
toggleBtn.Bind(wx.EVT_BUTTON, self.onHideShow)
hSizer.Add(toggleBtn, 0, wx.ALL, 5)
sortBtn = wx.Button(self, label="Sort buttons")
sortBtn.Bind(wx.EVT_BUTTON, self.onSort)
hSizer.Add(sortBtn, 0, wx.ALL, 5)
self.mainSizer.Add(hSizer, 0, wx.ALL|wx.CENTER, 5)
self.SetSizer(self.mainSizer)
#----------------------------------------------------------------------
def onHideShow(self, event):
"""
Hide / Show the buttons
"""
children = self.mainSizer.GetChildren()
for child in children:
widget = child.GetWindow()
if isinstance(widget, wx.Button):
if widget.IsShown():
widget.Hide()
else:
widget.Show()
#----------------------------------------------------------------------
def onSort(self, event):
"""
Sort the buttons
"""
children = self.mainSizer.GetChildren()
buttons = []
for child in children:
widget = child.GetWindow()
if isinstance(widget, wx.Button):
buttons.append(widget)
self.mainSizer.Detach(widget)
sortedBtns = sorted([btn for btn in buttons], key = lambda y: y.GetName())
# need to prepend them in reverse order to keep the two control buttons on the bottom
sortedBtns.reverse()
for btn in sortedBtns:
self.mainSizer.Prepend(btn, 0, wx.ALL|wx.CENTER, 5)
self.Layout()
########################################################################
class MyFrame(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title="Test", size=(600,800))
panel = MyPanel(self)
self.Show()
if __name__ == "__main__":
app = wx.App(False)
frame = MyFrame()
app.MainLoop()