views:

64

answers:

4

I have the wxPyhon following code

self.button1 = wx.Button(self, id=-1, label='Button1',pos=(8, 8), size=(175, 28))

self.button2 = wx.Button(self, id=-1, label='Button2',pos=(16, 8), size=(175, 28))

self.button1.Bind(wx.EVT_BUTTON, self.onButton)

self.button1.Bind(wx.EVT_BUTTON, self.onButton)

and I need to process the buttons on the below function according to the luanched event could someone provide an idea i.e

def button1Click(self,event):

if(event of button1 ) :

proccess code

if(event of button2 ):

proccess code

how can i know which button luanch the event

A: 

You could the buttons label to identify it like so

def onButton(self,event):
    buttonLabel =  event.GetEventObject().GetLabel()
    if buttonLabel == "Button1":
        doSomething()
    elif buttonLabel == "Button2":
        doSomethingElse()
volting
A: 

One option is to use the label (or ID...but that's usually more troublesome) to key off of, such as:

 def onButton(self, event):
    label = event.GetEventObject().GetLabel()
    if label == "foo":
         ...
    elif label == "bar":
         ....

Often times, I wish that it has a call back mechanism. So another option is to use lambda during the bind. See this tutorial

fseto
+1  A: 

You should have a function for each of them if there's different processing code.

self.button1 = wx.Button(self, id=-1, label='Button1',pos=(8, 8), size=(175, 28))

self.button2 = wx.Button(self, id=-1, label='Button2',pos=(16, 8), size=(175, 28))

self.button1.Bind(wx.EVT_BUTTON, self.onButton1)

self.button1.Bind(wx.EVT_BUTTON, self.onButton2)

def onButton1(self,event):
    # process code

def onButton2(self,event):
    # process code
leoluk
Also see http://wiki.wxpython.org/self.Bind%20vs.%20self.button.Bind or http://wiki.wxpython.org/Passing%20Arguments%20to%20Callbacks
Mike Driscoll
A: 

Personally, I like to get the button object itself:

button = event.GetEventObject()

Then I can use any of the button's methods, like GetName, GetId, or GetLabel. Setting the name is probably the easiest since sometimes I'll have two buttons with the same label.

myButton = wx.Button(self, label="blah blah", name="blah blah one")

Now you can be pretty sneaky. Somewhere in your program, you can have a dict that maps the button names with the methods they should run:

self.myDict = {"btnOne":methodOne, "btnTwo":methodTwo}

Then in your event handler, you can have something like

myButton = event.GetEventObject()
buttonName = myButton.GetName()
if buttonName in self.myDict:
    self.myDict[buttonName]()

See also http://wiki.wxpython.org/Passing%20Arguments%20to%20Callbacks or http://wiki.wxpython.org/self.Bind%20vs.%20self.button.Bind

Mike Driscoll