为什么wxPython的EVT_KILL_FOCUS用法表现异常?
我想让我的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()
意想不到的问题是,当我尝试将焦点从文本框切换到其他地方(无论是按Tab键还是鼠标点击)时,'文本失去焦点!'
的消息只打印了一次,然后就再也没有了,而且我无法再编辑文本框的内容。
这是正常现象吗?如果不是,我哪里做错了?
Python版本 2.7,wxPython版本 3.0.0.0,Windows 7 64位