0

我的代码,

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

我使用上面的代码动态创建多个按钮。所有创建的按钮都具有相同的参考名称。单击每个按钮时,我应该获得各自的个人 ID。但我得到的只是创建的最后一个按钮的 ID。如何打印按钮的单个 ID?

提前致谢!

4

2 回答 2

2

你的id在这里总是0

尝试将 idr 设置为唯一的(例如wx.NewId())或 -1

或者self.idr = 0按照你的__init__方法做

在旁注中,您应该将 self.button 设为列表并将新按钮附加到它...。

每次将 self.button 重新分配给新按钮可能会产生有趣的副作用 WRT 垃圾收集

于 2013-03-11T16:55:42.733 回答
0

您必须获取产生事件的对象:

#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 
于 2013-03-12T21:28:15.480 回答