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

2024-09-29 21:24:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我的密码

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?在

提前谢谢!在


Tags: posselfidbinddefbutton按钮one
2条回答

必须获取生成事件的对象:

#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 

你的id在这里总是0

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

或者在你的__init__方法中执行self.idr = 0

你应该做个旁注self.按钮一个列表和附加新按钮。。。。在

重新分配self.按钮对新按钮每次可能有有趣的副作用WRT垃圾收集

相关问题 更多 >

    热门问题