Search code examples
pythonwxpythonwxgrid

Processing Return key in wxGrid class


Recently I'm using python 2.7 and wx2.8 as a base of my application. Since that time I have problems in processing of Return key in my app. I have this error only on windows - in linux it works fine. All keys except Return/Numpad Return are processed. I put wx.TE_PROCESS_TAB|wx.TE_PROCESS_ENTER| wx.WANTS_CHARS style on my Frame and my Grid. I tried ON KEY DOWN and ON CHAR HOOK events- on frame and grid and grid renderer. My Return key is lost somewhere. Tried solutions from : What does wxWidgets' EVT_CHAR_HOOK do?

https://groups.google.com/forum/#!topic/wxpython-users/1RaaGxu62q4 (this was like perfect description of my problem but failed)

http://osdir.com/ml/python.wxpython/2004-03/msg00261.html

Any ideas, pls?

Regards Mike


Solution

  • There seem to be a few inconsistencies between the wxPython versions. Try following example:

    import wx
    import wx.grid
    
    class MainWindow(wx.Frame):
        def __init__(self, *args, **kwargs):
            wx.Frame.__init__(self, *args, **kwargs)
    
            self.panel = wx.Panel(self)
            self.grid = wx.grid.Grid(self.panel)
            self.grid.CreateGrid(3, 3)
            self.grid.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
            self.grid.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
            self.grid.Bind(wx.EVT_CHAR_HOOK, self.OnChar)
    
            self.sizer = wx.BoxSizer()
            self.sizer.Add(self.grid, 1)
    
            self.panel.SetSizerAndFit(self.sizer)  
            self.Show()
    
        # You may or may not want to add e.Skip() to your RETURN key handling.
        # If you do not call e.Skip(), the event is not propagated to the widget.
        # Depends on your app logic if that is something you want or not.
    
        def OnKeyDown(self, e):      
            # Python 2.7, wxPython 2.8 - Works, but more like EVT_CHAR_HOOK
            # Python 3.3, wxPython Phoenix - Never shows up
            code = e.GetKeyCode()
            if code in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:
                print("Return key down")
            else:
                e.Skip() 
    
        def OnKeyUp(self, e):
            code = e.GetKeyCode()
            if code in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:
                print("Return key up")
            else:
                e.Skip() 
    
        def OnChar(self, e):
            # Python 2.7, wxPython 2.8 - Never shows up
            # Python 3.3, wxPython Phoenix - Works
            code = e.GetKeyCode()
            if code in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:
                print("Return key char")
            else:
                e.Skip() 
    
    
    app = wx.App(False)
    win = MainWindow(None)
    app.MainLoop()