Reputation: 75
My code,
self.one = wx.Button(self, -1, "Add Button", pos = 100,20)
self.one.Bind(wx.EVT_BUTTON, self.addbt)
self.x = 50
self.idr = 0
self.btarr = []
def addbt(self.event)
self.button = wx.Button(self, self.idr, "Button 1", pos = (self.x,100))
self.button.Bind(wx.EVT_BUTTON, self.OnId)
self.idr+=1
self.x +=150
self.btarr.append(self.button)
def OnId(self, Event):
print "The id for the clicked button is: %d" % self.button.GetId()
#I wanna print id of indivual buttons clicked
I use the above code to create multiple buttons dynamically. All the created buttons have the same reference name. On clicking each button I should get respective individual ids. But all I am getting is the ID of the last button created. How do I print indivual Ids of the buttons?
Thanks in advance!
Upvotes: 0
Views: 279
Reputation: 85603
you must get the object that produced the event:
#create five buttons
for i in range(5):
# I use different x pos in order to locate buttons in a row
# id is set automatically
# note they do not have any name !
wx.Button(self.panel, pos=(50*i,50))
#bind a function to a button press event (from any button)
self.Bind((wx.EVT_BUTTON, self.OnId)
def OnId(self, Event):
"""prints id of pressed button"""
#this will retrieve the object that produced the event
the_button = Event.GetEventObject()
#this will give its id
the_id = the_button.GetId()
print "The id for the clicked button is: %d" % the_id
Upvotes: 0
Reputation: 113978
your id is always 0 here
try setting idr to something that is unique (eg wx.NewId()
) or -1
or doing self.idr = 0
in your __init__
method
on a side note you should make self.button a list and append new buttons to it....
reassigning self.button to the new button each time may have funny side effects WRT garbage collection
Upvotes: 2