我希望我的wxPython应用程序在文本输入小部件失去焦点时触发事件。我遵循了这里的教程,其中描述了使用wx.EVT_KILL_FOCUS
。然而,我得到了意想不到的行为
以下代码运行良好:
import wx
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Focus Tutorial 1a")
panel = wx.Panel(self, wx.ID_ANY)
txt = wx.TextCtrl(panel, wx.ID_ANY, "")
txt.Bind(wx.EVT_KILL_FOCUS, self.onTextKillFocus)
"""
This next line seems to be important for working correctly,
but I don't understand why:
"""
txt.Bind(wx.EVT_SET_FOCUS, self.onTextFocus)
btn = wx.Button(panel, wx.ID_ANY, "Test")
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(txt, 0, wx.ALL, 5)
sizer.Add(btn, 0, wx.ALL, 5)
panel.SetSizer(sizer)
def onTextFocus(self, event):
print "text received focus!"
def onTextKillFocus(self, event):
print "text lost focus!"
if __name__ == '__main__':
app = wx.App()
frame = MyForm().Show()
app.MainLoop()
当我从文本控件来回切换到按钮,或者点击文本控件的内部或外部时,我会收到我想要的焦点消息。
然而,当我进行以下(合理的?)编辑时,情况会恶化:
import wx
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Focus Tutorial 1a")
panel = wx.Panel(self, wx.ID_ANY)
txt = wx.TextCtrl(panel, wx.ID_ANY, "")
txt.Bind(wx.EVT_KILL_FOCUS, self.onTextKillFocus)
"""
This next line seems to be important for working correctly,
but I don't understand why:
"""
## txt.Bind(wx.EVT_SET_FOCUS, self.onTextFocus)
btn = wx.Button(panel, wx.ID_ANY, "Test")
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(txt, 0, wx.ALL, 5)
sizer.Add(btn, 0, wx.ALL, 5)
panel.SetSizer(sizer)
def onTextFocus(self, event):
print "text received focus!"
def onTextKillFocus(self, event):
print "text lost focus!"
if __name__ == '__main__':
app = wx.App()
frame = MyForm().Show()
app.MainLoop()
意外的行为是,当我尝试将焦点从文本框更改为其他任何内容(选项卡或鼠标单击)时,'text lost focus!'
消息将打印一次,再也不会打印,并且我无法再编辑文本控件的内容。
这是预期行为吗?如果没有,我做错了什么
Python版本2.7,wxPython版本3.0.0.0,Windows 7 64位
正如wxEvent::Skip()文档中所解释的,您几乎应该总是为非命令事件调用它,因为您不想阻止默认处理的发生。