本文介绍了wxpython 无法捕获 EVT_KEY_DOWN enent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法捕获 EVT_KEY_DOWN 事件.但是可以捕获EVT_KEY_UP.
Python 版本: 2.7.3
wxPython 版本: 2.8.12.1 (gtk2-unicode)
系统信息: Mint 14 Nadia,Linux 3.5.0-17-generic(x86_64)
以下是我的代码

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()

推荐答案

我一直在捕获 wx.EVT_KEY_DOWN 和 wx.EVT_KEY_UP 时遇到问题.原因的解释有点超出我的理解,但我知道切换到 EVT_CHAR_HOOK 通常对我有用.尝试这样的事情:

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()

如果您希望事件继续传播,您可能还想将 event.Skip() 放在 OnKeyPress 的底部.

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

这篇关于wxpython 无法捕获 EVT_KEY_DOWN enent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 00:31