wxPython: binding wx.EVT_CHAR_HOOK disables TextCtrl backspace

谁说胖子不能爱 提交于 2019-12-11 01:33:42

问题


I have a wx.TextCtrl and I want to be able to type in it, but also detect key presses such as UP, DOWN, RETURN, ESC.

So I binded wx.EVT_KEY_DOWN to recognize any key press, and wx.EVT_CHAR_HOOK to do the same thing even when TextCtrl has focus.

self.Bind(wx.EVT_KEY_DOWN, self.keyPressed)
self.Bind(wx.EVT_CHAR_HOOK, self.keyPressed)

Key presses UP, DOWN, RETURN, ESC were recognized and working fine, but due to binding EVT_CHAR_HOOK I cannot use LEFT RIGHT BACKSPACE SHIFT anymore when I type in the TextCtrl.

Any suggestions?


回答1:


You should call event.Skip() at the end of the event handler to propagate it further. This works for me:

import wx

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.panel = wx.Panel(self)
        self.text = wx.TextCtrl(self.panel)
        self.text.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.text.Bind(wx.EVT_KEY_UP, self.OnKeyUp)

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.text, 1)

        self.panel.SetSizerAndFit(self.sizer)  
        self.Show()

    def OnKeyDown(self, e):      
        code = e.GetKeyCode()
        if code == wx.WXK_ESCAPE:
            print("Escape")
        if code == wx.WXK_UP:
            print("Up")
        if code == wx.WXK_DOWN:
            print("Down")
        e.Skip()

    def OnKeyUp(self, e):
        code = e.GetKeyCode()
        if code == wx.WXK_RETURN:
            print("Return")
        e.Skip()


app = wx.App(False)
win = MainWindow(None)
app.MainLoop()


来源:https://stackoverflow.com/questions/20416650/wxpython-binding-wx-evt-char-hook-disables-textctrl-backspace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!