trapping character events

Help
2008-10-03
2013-05-01
  • Jeff Graver
    Jeff Graver
    2008-10-03

    Making good progess now.  Have my first form nearly complete.

    I would like to trap the <Esc> key at the wxFrame level, to have it close the form.  In this current incarnation of the form, I started with a wxFrame, put a wxPanel on it, then filled this first panel with lots of stuff.

    I have tried binding the wx.EVT_CHAR event on both the frame and the panel, but I can't find a place on the form that will trigger these events.  That is, I ran the form under the debugger and set breakpoints on both of the character trapping events.  Then I clicked on various locations in the form and tried pressing an <Esc>.  (For the record, I also tried a case where _any_ key would close the form, to no avail).

    What am I missing?

    Here's the simplest test case I could think of:

    #Boa:Frame:Frame1

    import wx

    def create(parent):
        return Frame1(parent)

    [wxID_FRAME1, wxID_FRAME1PANEL1,
    ] = [wx.NewId() for _init_ctrls in range(2)]

    class Frame1(wx.Frame):
        def _init_ctrls(self, prnt):
            # generated method, don't edit
            wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
                  pos=wx.Point(132, 132), size=wx.Size(400, 250),
                  style=wx.DEFAULT_FRAME_STYLE, title='Frame1')
            self.SetClientSize(wx.Size(392, 223))
            self.Bind(wx.EVT_CHAR, self.OnFrame1Char)

            self.panel1 = wx.Panel(id=wxID_FRAME1PANEL1, name='panel1', parent=self,
                  pos=wx.Point(208, 96), size=wx.Size(200, 100),
                  style=wx.TAB_TRAVERSAL)
            self.panel1.Bind(wx.EVT_CHAR, self.OnPanel1Char)

        def __init__(self, parent):
            self._init_ctrls(parent)

        def OnFrame1Char(self, event):
            if event.GetKeyCode() == wx.WXK_ESCAPE:
                self.Close()
            else:
                event.Skip()

        def OnPanel1Char(self, event):
            if event.GetKeyCode() == wx.WXK_ESCAPE:
                self.Close()
            else:
                event.Skip()

    if __name__ == '__main__':
        app = wx.PySimpleApp()
        frame = create(None)
        frame.Show()

        app.MainLoop()

     
    • Hi,

      You need to set the style wx.WANTS_CHARS, and as you use a panel (which you should) you just set it on the panel.

      For some reason the escape doesn't trigger it and I can only seem to able to catch it on the wx.EVT_KEY_UP event.

      Also when I check it in the wxPython demo I also get it in the EVT_CHAR event - a little mistery.

      This type of question, i.e. not strictly Boa related, is probably better asked on the wxPython list (wxpython-users@lists.wxwidgets.org).

      Hope this helps
      Werner