Reputation: 81
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()
I want to make multiple wx.button
. The problem is that I want to create a button based on the value of the loop and give a value to the generated button label. I wonder how I can create this effectively.
Do I have to create the wx.button
variables one by one, just like the code I uploaded as examples? Or I want to know if I can make it into a loop.
Upvotes: 0
Views: 382
Reputation: 22443
The trick is not to just create lots of buttons but to make them usable as well.
In that you must be able to identify them, if they are clicked on.
You also have to be able to position them.
Here is one
way that you can do it.
I am using a sizer
to place them and assigning an Identity with wx.NewId
to each button.
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()
Upvotes: 3