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 に答える