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

时间:2015-07-23 19:05:10

标签: python python-3.x wxpython

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

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

1 个答案:

答案 0 :(得分: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")

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

相关问题