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

问题描述 投票:1回答:1

我在处理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的孩子感到困惑。

python python-3.x wxpython
1个回答
1
投票

您可以做的是将焦点杀死和焦点选择绑定到函数,像这样:

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

希望这有帮助,如果我没有清楚/正确地回答我,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.