2013-03-11 82 views
0

我的代碼,如何在wxpython中打印具有相同名稱的多個按鈕的ID?

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

您的ID總是0這裏

嘗試設置IDR的東西,是獨一無二的(如wx.NewId())或-1

或上側在__init__方法

self.idr = 0注意:您應該使self.button列表並追加新的按鈕...

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

+0

謝謝!實際上我在原始程序中就是這樣做的。即使我創建了一個按鈕列表,它如何幫助我獲取相應的ID? – 2013-03-12 04:19:41

+0

GetId()獲取ID ...但是你在設置'self.idr = 0'後立即將它設置爲self.idr,因此你總是將該ID設置爲零 – 2013-03-12 15:21:50

+0

謝謝Joran,我已經修改了! – 2013-03-12 16:21:00

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 
+0

工程太棒了!非常感謝! – 2013-03-13 06:35:29

+0

@SwayamS。您必須接受和/或向上提供您認爲有用的答案。你沒有接受你在SO上提出的任何問題。 – joaquin 2013-03-13 07:27:57

+0

我不知道我應該這樣做!再次感謝! – 2013-03-14 09:55:44

相關問題