wxPython 版本之间似乎存在一些不一致之处。试试下面的例子:
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()