如何在wxpython中打印具有相同名称的多个按钮的ID?
我的代码如何在wxpython中打印具有相同名称的多个按钮的ID?,python,wxpython,wxwidgets,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,10
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
提前谢谢 您的id在此始终为0 尝试将idr设置为唯一的值(例如
wx.NewId()
)或-1
或者在\uuuu init\uuuu
方法中执行self.idr=0
在旁注上,你应该把self.button列为一个列表,并在其中添加新的按钮
每次将self.button重新指定给新按钮可能会产生有趣的副作用WRT garbage collection您必须获取生成事件的对象:
#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?GetId()获取id。。。但是在设置self.idr=0之后,您就将其设置为self.idr,因此您总是将id设置为零,这很好!非常感谢你@斯韦尔斯。你必须接受和/或投票选出你认为有用的答案。你还没有接受任何关于你的问题的答案。我不知道我应该这么做!再次感谢!