獲取按鈕排序有點棘手,但關鍵是找到要排序的東西。您可以使用按鈕標籤或按鈕名稱。我和後者一起去了。以下代碼還演示瞭如何顯示/隱藏按鈕:
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()
謝謝,這是我最終做的。花了一段時間才意識到,雖然我分開之前我需要隱藏他們的物品,否則他們會保持可見但不受sizer的影響。 – phimath