wxpython can't capture EVT_KEY_DOWN enent

2019-05-19 00:42发布

问题:

I can't capture EVT_KEY_DOWN event. But can capture EVT_KEY_UP.
Python version : 2.7.3
wxPython version : 2.8.12.1 (gtk2-unicode)
system info: Mint 14 Nadia , Linux 3.5.0-17-generic(x86_64)
Following is my code

#!/usr/bin/env python

import sys, os
import wx
class  WinFrame(wx.Frame):
    def __init__(self, parent, title):
        super(WinFrame, self).__init__(parent, 
                                       title=title,
                                       size=(400,400))
        self.panel = wx.Panel(self,-1, size=(400,400))
        self.panel.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.panel.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
    def OnKeyUp(self, event):
        print 'up'

    def OnKeyDown(self, event):
        print 'down'

class PicSampleApp(wx.App):
    def __init__(self):
        super(PicSampleApp, self).__init__(0)

    def createFrame(self):
        self.frame = WinFrame(None, "test")
        self.frame.Show(True)
        self.SetTopWindow(self.frame)


app = PicSampleApp()
app.createFrame()
app.MainLoop()

回答1:

I've always had problems with capturing wx.EVT_KEY_DOWN and wx.EVT_KEY_UP. The explanation of why is a bit over my head, but I know that switching to EVT_CHAR_HOOK usually does the trick for me. Try something like this:

#!/usr/bin/env python

import sys, os
import wx
class  WinFrame(wx.Frame):
    def __init__(self, parent, title):
        super(WinFrame, self).__init__(parent, 
                                       title=title,
                                       size=(400,400))
        self.panel = wx.Panel(self,-1, size=(400,400))
        self.panel.Bind(wx.EVT_CHAR_HOOK, self.OnKeyPress)

    def OnKeyPress(self, event):
        keyCode = event.GetKeyCode()
        if keyCode == wx.WXK_DOWN:
            print 'down'
        elif keyCode == wx.WXK_UP:
            print 'up'

class PicSampleApp(wx.App):
    def __init__(self):
        super(PicSampleApp, self).__init__(0)

    def createFrame(self):
        self.frame = WinFrame(None, "test")
        self.frame.Show(True)
        self.SetTopWindow(self.frame)

app = PicSampleApp()
app.createFrame()
app.MainLoop()

You might also want to put event.Skip() at the bottom of OnKeyPress if you want the event to continue propagating.