0

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!

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I have actually done it like that in my original program. Even if I create a list of buttons, how do it help me in getting the respective ids?
GetId() gets the id ... but you are setting it to self.idr right after you set self.idr=0 so you are always setting the id to zero
0

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 

2 Comments

@SwayamS. You have to accept and/or upvote the answers you find useful. You have not accepted any of the answers you got for your question on SO.
I didn't know I was supposed to do that! Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.