wxPython EVT_CHAR not called when a panel is added to a frame
Question: I need to bind the EVT_CHAR event for a GUI application I am developing using
wxPython. I tried the following and I cann understand the beahviour of the
code.

    
    
    import wx
    import wx.lib.agw.flatnotebook as fnb
    
    class DemoApp(wx.App):
    
        def __init__(self):
            wx.App.__init__(self, redirect=False)
    
            self.mainFrame = DemoFrame()
            self.mainFrame.Show()
    
        def OnInit(self):
            return True
    
    
    class DemoFrame(wx.Frame):
    
        def __init__(self):
            """Constructor"""
            wx.Frame.__init__(self, None, wx.ID_ANY,
                              "FlatNotebook Tutorial",
                              size=(600,400)
                              )
            panel = wx.Panel(self)
            button = wx.Button(panel, label="Close", pos=(125, 10), size=(50, 50))
    
            self.Bind(wx.EVT_CHAR, self.character)
    
        def character(self, event):  
            print "Char keycode : {0}".format(event.GetKeyCode())
    
    if __name__ == "__main__":
        app = DemoApp()
        app.MainLoop()
    

The character function never gets called. However, when I comment out the two
lines call to the Frame constructor, I character function is called. Adding a
panel to the frame seems to interfere with the binding of the frame's
EVT_CHAR.

How do I address this problem? Am I doing something wrong in my code?


Answer: The problem is that you are catching events that happen to the frame, but the
frame is not in focus. The button is. In wxPython, events are sent to the
widget in focus. If you add this to the end of your **init** , it works:

    
    
    self.SetFocus()
    

However, if you change the focus to the button, then it will stop working
again. See also:

  * [wxpython capture keyboard events in a wx.Frame](http://stackoverflow.com/questions/8707160/wxpython-capture-keyboard-events-in-a-wx-frame)
  * <http://www.blog.pythonlibrary.org/2009/08/29/wxpython-catching-key-and-char-events/>
  * <http://wxpython-users.1045709.n5.nabble.com/Catching-key-events-from-a-panel-and-follow-up-to-stacked-panels-td2360109.html>

