wxPython: Binding Multiple Widgets to the Same Handler

If you’ve been in the wxPython community for more than a couple months, you will probably recognize the following question: “How do I bind multiple buttons to the same event handler and make them do different things?” Well, this article will show you how to do exactly that.

Note: This article is based on some code from a previous article on buttons from this very blog!

Let’s Get Started

To begin, we need to write some code that actually contains multiple buttons. We will go through an example that shows two different ways to get the button object so you can manipulate your program as needed. Here’s the code you’ve been waiting for:

import wx

########################################################################
class MyForm(wx.Frame):
 
    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Button Tutorial")
        panel = wx.Panel(self, wx.ID_ANY)
        
        sizer = wx.BoxSizer(wx.VERTICAL)
        buttonOne = wx.Button(panel, label="One", name="one")
        buttonTwo = wx.Button(panel, label="Two", name="two")
        buttonThree = wx.Button(panel, label="Three", name="three")
        buttons = [buttonOne, buttonTwo, buttonThree]
        
        for button in buttons:
            self.buildButtons(button, sizer)
            
        panel.SetSizer(sizer)
        
    #----------------------------------------------------------------------
    def buildButtons(self, btn, sizer):
        """"""
        btn.Bind(wx.EVT_BUTTON, self.onButton)
        sizer.Add(btn, 0, wx.ALL, 5)
        
    #----------------------------------------------------------------------
    def onButton(self, event):
        """
        This method is fired when its corresponding button is pressed
        """
        button = event.GetEventObject()
        print "The button you pressed was labeled: " + button.GetLabel()
        print "The button's name is " + button.GetName()
        
        button_id = event.GetId()
        button_by_id = self.FindWindowById(button_id)
        print "The button you pressed was labeled: " + button_by_id.GetLabel()
        print "The button's name is " + button_by_id.GetName()
 
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

To start, we create three button objects. Then to make things slightly less messy, we put them into a list and iterate over the list to add the buttons to a sizer and bind them to an event handler. This is a good way to cut down on spaghetti code (i.e. copy and pasted code) and makes it a little cleaner and easier to debug. Some people go ahead and create some elaborate helper methods like buildButtons that can handle other widgets and are more flexible.

The part we really care about though is the event handler itself. The easiest way to get the widget in the event handler is by calling the event object’s GetEventObject() method. That will return the widget and then you can do whatever you like. Some people will change the widget’s value or label, others will use the widgets ID or unique name and set up some conditional structures to do something if this button is pressed and do something else if a different button is pressed. The functionality is up to you.

The second way to get the widget is a two-step process where we need to extract the ID from the event using its GetID() method. Then we pass that result to our frame object’s FindWindowById() method and we once again have the widget in question.

Wrapping up

Now you know the “secret” of binding multiple widgets to the same event handler. Go forth and code like there’s no tomorrow and create something amazing! The code can be downloaded on the new blog’s Mercurial repository.

Additional Resources

6 thoughts on “wxPython: Binding Multiple Widgets to the Same Handler”

  1. Pingback: Frattanto nella blogosfera #27 « Ok, panico

  2. I didn’t mean to imply that this article was about less code. It’s not. I rarely do this sort of thing in my own code, although I have found the methods for acquiring the calling widget handy. This article is just to answer a common question I see in the wxPython mailing list and on StackOverflow.

  3. Pingback: WxPython: Multiple Widgets in a Child Window | PHP Developer Resource

  4. Pingback: PySide: Connecting Multiple Widgets to the Same Slot - The Mouse Vs. The Python

Comments are closed.