如何在wxpython中打印多个具有相同名称的按钮?

时间:2013-03-11 16:24:55

标签: python wxpython wxwidgets

我的代码,

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?

提前致谢!

2 个答案:

答案 0 :(得分:2)

你的身份证总是0

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

或在self.idr = 0方法

中执行__init__

在旁注上你应该自我按钮,然后在它上面添加新按钮......

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

答案 1 :(得分: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