import wx
class MainFream(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None,title='test', size=(505,500), style=wx.DEFAULT_FRAME_STYLE)
self.MainPanel = wx.Panel(self)
test = []
for i in range(1,11):
test.append(i)
print(test)
self.button1 = wx.Button(self.MainPanel, label=str(test[0]), pos=(0, 0))
self.button2 = wx.Button(self.MainPanel, label=str(test[1]), pos=(100, 0))
self.button3 = wx.Button(self.MainPanel, label=str(test[2]), pos=(200, 0))
self.button4 = wx.Button(self.MainPanel, label=str(test[3]), pos=(300, 0))
self.button5 = wx.Button(self.MainPanel, label=str(test[4]), pos=(400, 0))
self.button6 = wx.Button(self.MainPanel, label=str(test[5]), pos=(0, 50))
self.button7 = wx.Button(self.MainPanel, label=str(test[6]), pos=(100, 50))
self.button8 = wx.Button(self.MainPanel, label=str(test[7]), pos=(200, 50))
self.button9 = wx.Button(self.MainPanel, label=str(test[8]), pos=(300, 50))
self.button10 = wx.Button(self.MainPanel, label=str(test[9]), pos=(400, 50))
self.button11 = wx.Button(self.MainPanel, label='...', pos=(0, 100))
self.button12 = wx.Button(self.MainPanel, label='...', pos=(100, 100))
self.button13 = wx.Button(self.MainPanel, label='...', pos=(200, 100))
self.button14 = wx.Button(self.MainPanel, label='...', pos=(300, 100))
self.button15 = wx.Button(self.MainPanel, label='...', pos=(400, 100))
if __name__ == '__main__':
app = wx.App()
fream = MainFream()
fream.Show()
app.MainLoop()
我想制作多个wx.button
。问题是我想根据循环的值创建一个按钮,并为生成的按钮标签赋值。我想知道如何有效地创造这个。
我是否必须逐个创建wx.button
变量,就像我上传的代码一样?或者我想知道我是否可以将它变成循环。
答案 0 :(得分:2)
诀窍不仅仅是创建大量按钮,而是让它们也可用
如果点击它们,你必须能够识别它们
你还必须能够定位它们
以one
的方式可以做到这一点
我使用sizer
放置它们并为每个按钮分配一个wx.NewId
标识。
import wx
class MainFream(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None,title='test', size=(505,500), style=wx.DEFAULT_FRAME_STYLE)
self.MainPanel = wx.Panel(self)
test = []
button_id = []
for i in range(1,21):
test.append(i)
button_id.append(wx.NewId())
self.button = []
for i in range(len(test)):
self.button.append(wx.Button(self.MainPanel,button_id[i],label=(str(test[i]))))
self.button[i].Bind(wx.EVT_BUTTON, self.OnButton)
sizer = wx.FlexGridSizer(0, 5, 5, 5)
for i in self.button:
sizer.Add(i, 0, wx.ALL, 0)
self.MainPanel.SetSizer(sizer)
def OnButton(self, event):
Id = event.GetId()
Obj = event.GetEventObject()
print ("Button Id",Id)
print ("Button Pressed:",Obj.GetLabelText())
if __name__ == '__main__':
app = wx.App()
fream = MainFream()
fream.Show()
app.MainLoop()