我希望我的wxPython应用程序在文本输入窗口小部件失去焦点时触发事件。我已经按照教程here进行了操作,该教程描述了使用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位