EVT_CHAR 从不调用处理程序

EVT_CHAR never calls handler

我在接收自定义控件上的 EVT_CHAR 事件时仍然遇到很大的麻烦。在互联网上搜索了几天后,我不知道为什么我没有收到这些事件。

我知道关于 EVT_CHAR 的问题很多 - 我已经通读了很多,但是 none 提供的解决方案似乎有效。我已确保以下内容:

我试过在框架上使用和不使用 wx.WANTS_CHARS。
我已经尝试绑定到框架和控件,无论有没有源参数指向每个。 没有其他与键盘相关的事件绑定,但是我 按照下面的代码配置了加速器。

我也尝试扩展 wx.TextEntry。我试图追查的一种可能性是自定义控件不会接收这些事件,因为它似乎不是文本输入控件,并且该事件仅在 non-readonly/editable 控件上触发。我没有运气弄清楚这一点。

版本信息:
我正在 Python 3.7 上进行测试,最常见的是在 3.6 上进行测试。
wxPython 版本 4.0.3
Windows 10.1709 企业

以下是我的框架class中的代码片段,负责构建GUI并监听这些事件。我还包含了 EVT_CHAR.

的(目前无用的)事件处理程序
def do_create_gui(self):
    classname = self.__class__.__name__

    app = wx.App()
    AppTitle = "%s: %s" % (self._comms.port, classname)
    size = wx.Size(700, 450)
    frame = wx.Frame(None, title=AppTitle, size=size)
    panel = wx.Panel(frame)
    panelSizer = wx.BoxSizer(wx.VERTICAL)
    sizer = wx.BoxSizer(wx.VERTICAL)

    # Configure Menu
    fileMenu = wx.Menu()
    copyitem = fileMenu.Append(wx.ID_COPY, "&Copy\tCtrl-C")
    pasteitem = fileMenu.Append(wx.ID_PASTE, "&Paste\tCtrl-V")
    fileMenu.AppendSeparator()
    brkitem = fileMenu.Append(wx.ID_ANY, "&Break\tCtrl-B")
    fileMenu.AppendSeparator()
    quititem = fileMenu.Append(wx.ID_EXIT, "&Quit")

    helpMenu = wx.Menu()
    hotkeyitem = helpMenu.Append(wx.ID_ANY, "Program &Shortcuts")

    menubar = wx.MenuBar()
    menubar.Append(fileMenu, '&File')
    menubar.Append(helpMenu, '&Help')
    frame.SetMenuBar(menubar)

    self._terminal = TerminalCtrl(panel)
    self._terminal.SetSpacing(0)
    self._terminal.SetWrap(True)

    sizer.Add(self._terminal, 1, wx.EXPAND)
    panelSizer.Add(panel, 1, wx.EXPAND)
    panel.SetSizer(sizer)
    frame.SetSizer(panelSizer)
    frame.SetMinSize(wx.Size(313, 260))
    frame.Show()

    # Set up accelerators
    accelC = wx.AcceleratorEntry(wx.ACCEL_CTRL, ord('C'), wx.ID_COPY)
    accelV = wx.AcceleratorEntry(wx.ACCEL_CTRL, ord('V'), wx.ID_PASTE)
    accelB = wx.AcceleratorEntry(wx.ACCEL_CTRL, ord('B'), brkitem.GetId())
    accel = wx.AcceleratorTable([accelC, accelV, accelB])
    frame.SetAcceleratorTable(accel)

    # Bind on window events
    frame.Bind(wx.EVT_CLOSE, self.onClose)
    self._terminal.Bind(wx.EVT_CHAR, self.onChar)

    # Bind Menu handlers
    frame.Bind(wx.EVT_MENU, self.onClose, quititem)
    frame.Bind(wx.EVT_MENU, self.showHotkeys, hotkeyitem)
    frame.Bind(wx.EVT_MENU, lambda e: self.onCopy(), copyitem)
    frame.Bind(wx.EVT_MENU, lambda e: self.onPaste(), pasteitem)
    frame.Bind(wx.EVT_MENU, lambda e: self.send_break(), brkitem)

    # Register for events from Serial Communications thread
    EVT_SERIAL(frame, self.onSerialData)

    # Ensure the terminal has focus
    self._terminal.SetFocus()

    self._wxObj = frame
    self._tLock.release()
    app.MainLoop()

def onChar(self, event):
    code = event.GetUnicodeKey()

    if code == wx.WXK_NONE:
        code = event.GetKeyCode()

    if (not 27 < code < 256) or event.HasAnyModifiers():
        # So we don't consume the event
        print('We don\'t process your kind here! (%d)' % code)
        event.Skip()
        return

    print("CHAR: %s(%d)" % (chr(code), code))

关于自定义控件,这里是定义。

import wx
from wx.lib.scrolledpanel import ScrolledPanel

class TerminalCtrl(ScrolledPanel, wx.Window):
    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.TAB_TRAVERSAL,
                 name=wx.ControlNameStr):
        pass
    pass

如果您没有得到针对 window 的 wxEVT_CHAR,这意味着某些东西正在处理 wxEVT_KEY_DOWN 而不是跳过它。这似乎不会在您的代码中的任何地方发生,所以我唯一的猜测是它是由您使用的 ScrolledPanel class 完成的。尝试使用普通的 wxWindow,你真的应该得到这些事件。

我曾尝试做类似的事情,但它对我也不起作用。

根据我的实验,问题是由 TAB_TRAVERSAL 标志引起的。如果您的 window 是使用此标志创建的,则 TAB_TRAVERSAL 机制似乎会吸收所有 EVT_CHAR 事件并且您的处理程序永远不会被调用。这可能是一个错误,但我不确定。

此标志有时会默认设置:对于 wx.Panel 这是默认的 window 样式,但对于 wx.Window 则不是。在我的测试程序中,当我尝试在面板中获取按键时,它不起作用,但如果我使用 wx.Window,它就起作用了。当我更改 Panel 的样式参数以避免设置 TAB_TRAVERSAL 标志时,这也有效。

我还尝试处理 EVT_CHAR_HOOK 事件,并调用 event.DoAllowNextEvent()。文档(我明智地使用了这个词)说这是必要的,但显然不是。

这是我的测试程序的实际工作版本。通过试验它,您可以(某种程度上)弄清楚发生了什么。评论各种选项或从 wx.Panel 更改为 wx.Window 非常有启发性。

import wx

class MainWindow(wx.Frame):
    def __init__(self):
        super().__init__(None, title="Char test")
        self.label = wx.StaticText(self, label="Label")
        self.panel = DaPanel(self)
        bs = wx.BoxSizer(wx.VERTICAL)
        bs.Add(self.label, wx.SizerFlags().Expand())
        bs.Add(self.panel, wx.SizerFlags(1).Expand())
        self.SetSizerAndFit(bs)
        self.SetAutoLayout(True)
        self.SetSize(wx.Size(800, 600))
        self.Centre()
        self.Show()

        # self.Bind(wx.EVT_CHAR_HOOK, self.do_char_hook)

    def do_char_hook(self, event):
        # The functions DoAllowNextEvent and Skip seem to do the same thing
        event.DoAllowNextEvent()
        event.Skip()
        # Calling either causes the EVT_KEY_DOWN event to occur for default
        # wxPanel but make no difference for wxWindows.

class DaPanel(wx.Window):
    def __init__(self, parent):
        # default style wxPanel won't ever get EVT_CHAR events
        # default style wxWindow will get EVT_CHARs
        super().__init__(parent)
        self.Bind(wx.EVT_CHAR, self.do_char)
        # self.Bind(wx.EVT_KEY_DOWN, self.do_down)

    def do_char(self, event):
        print("char", event.GetUnicodeKey())

    def do_down(self, event):
        print("down", event.GetUnicodeKey(), self.HasFocus())
        # if you run this handler you must Skip()
        # or else no char event ever happens
        event.Skip()

def main():
    app = wx.App()
    mw = MainWindow()
    mw.Show(True)
    app.MainLoop()

main()