A question about event handlers with wxPython

Mike Driscoll kyosohma at gmail.com
Tue Jan 15 10:21:50 EST 2008


On Jan 15, 9:04 am, "Erik Lind" <el... at spamcop.net> wrote:
> > def HandleSomething(self, event):
> >    generating_control = event.GetEventObject()
> >    print generating_control
>
> > HTH,
>
> Thank you.That is what I was looking for, but as often seems the case, one
> thing exposes another. Is there any way to listen for events without
> specifically binding to a handler (it seems one cannot bind an event to two
> handlers?)? One could do so with globals, but I'm trying to avoid that.
>
> For example, "press any button to stop"
>
> def HandleSomething(self, event):
>     .................
>      while generating_control: == something:
>             run
>             else
>             stop

There are a number of ways to handle this. You could just bind the
parent to the handler. Something like this:

self.Bind(wx.EVT_BUTTON, self.onStop)

This will bind all button presses to the onStop handler. You could
also do something like this:

self.Bind(wx.EVT_BUTTON, self.onBtnStop)

def onBtnStop(self, event):
    #do something
    event.Skip()

By calling the Skip() method, it will propagate the event and look for
another handler, which in this case would be the onStop handler. On
Windows, you will most likely need to make a wx.Panel be the parent of
the rest of the widgets to have this effect.

My complete test code is below.

<code>

import wx

class Closer(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, title='Test Frame')
        panel = wx.Panel(self, -1)

        sizer = wx.BoxSizer(wx.VERTICAL)
        btn1 = wx.Button(panel, wx.ID_ANY, 'Button 1')
        btn2 = wx.Button(panel, wx.ID_ANY, 'Button 2')
        btn3 = wx.Button(panel, wx.ID_ANY, 'Button 3')

        sizer.Add(btn1)
        sizer.Add(btn2)
        sizer.Add(btn3)

        self.Bind(wx.EVT_BUTTON, self.onDone)
        self.Bind(wx.EVT_BUTTON, self.onStop, btn1)
        panel.SetSizer(sizer)

    def onStop(self, event):
        print 'Stop!'
        event.Skip()

    def onDone(self, event):
        print 'Done!'

if __name__ == '__main__':
    app = wx.PySimpleApp()
    Closer().Show()
    app.MainLoop()

</code>

FYI: There is an excellent wxPython group that you can join over on
the wxPython.org website.

Mike



More information about the Python-list mailing list