wxPython (Phoenix) 中的全局事件处理程序

Global event handlers in wxPython (Phoenix)

我在尝试处理 phoenix fork wxPython 3 中的焦点事件时遇到问题。

如果 TextCtrl 仍具有默认值,我将尝试在它获得焦点时清除该值,然后如果用户未输入其他值,则在离开焦点时恢复该默认值。

这是我的处理程序:

def on_enter(self, event):
    control = wx.Window.FindFocus()
    if control.Id in TEXT_MAPPING.keys():
        if control.Value == TEXT_MAPPING[control.Id]:
            control.SetValue('')
    exit_control = event.GetWindow()
    if exit_control.Id in (TEXT_MAPPING.keys()):
        if not exit_control.GetValue():
            exit_control.SetValue(TEXT_MAPPING[exit_control.Id])
    event.Skip()

处理程序本身工作正常,尽管它有点笨拙。我的问题是我想在全局级别绑定它,这样每当任何 wx.EVT_SET_FOCUS 事件被触发时,我都可以让它由这个函数处理。

我找到了这个:

导入 wx

class MyApp(wx.App):
     def FilterEvent(self, evt):
         print evt
         return -1

app = MyApp(redirect=False)
app.SetCallFilterEvent(True)
frm = wx.Frame(None, title='Hello')
frm.Show()
app.MainLoop()

但我对如何将事件传递给 MyApp 的 children 感到困惑。

你可以做的是将 focus kill 和 focus select 绑定到函数,像这样:

self.user_text.Bind(wx.EVT_SET_FOCUS, self.on_focus_username)
self.user_text.Bind(wx.EVT_KILL_FOCUS, self.on_deselect_username)

其中 self 是 TextCtrl "user_text" 所在的面板。

函数可能如下所示:

def on_focus_username(self, event):
    if self.user_text.GetForegroundColour() != wx.BLACK:
        self.user_text.SetForegroundColour(wx.BLACK)
        # Clear text when clicked/focused
        self.user_text.Clear()

def on_deselect_username(self, event):
    if self.user_text.GetLineLength(0) is 0:
        self.user_text.SetForegroundColour(wx.Colour(192, 192, 192))
        # Put a default message when unclicked/focused away
        self.user_text.SetValue("Enter Username")

希望这对您有所帮助,如果我没有回答某些问题 clearly/correctly 让我知道。