wxPython - 防止相同的警告对话框出现两次
问题描述:
我有一个textctrl接受用户输入。我想在用户输入文本后查看文本是否也在预定义的单词列表中。当textctrl失去焦点时,我可以做这个检查。我也可以设置它来检查何时按下回车键。然而,如果我这样做,输入被检查两次(不是很大的交易,但没有必要)。如果输入不正确(该单词不在列表中),则弹出2个错误对话框。这并不理想。最好的解决办法是什么?wxPython - 防止相同的警告对话框出现两次
编辑:如果我不清楚,如果输入不正确并且输入命中,则会弹出2个警告。这会导致一个对话框出现,这会窃取焦点,导致第二个出现。
答
此演示代码符合您的标准。
你应该可以在一个单独的文件中完整地运行它。
import sys; print sys.version
import wx; print wx.version()
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "hello frame")
self.inspected = True
self.txt = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
self.txt.SetLabel("this box must contain the word 'hello' ")
self.txt.Bind(wx.EVT_TEXT_ENTER, self.onEnter)
self.txt.Bind(wx.EVT_KILL_FOCUS, self.onLostFocus)
self.txt.Bind(wx.EVT_TEXT, self.onText)
def onEnter(self, e):
self.inspectText()
def onLostFocus(self, e):
self.inspectText()
def onText(self, e):
self.inspected = False
def inspectText(self):
if not self.inspected:
self.inspected = not self.inspected
if 'hello' not in self.txt.GetValue():
self.failedInspection()
else:
print "no need to inspect or warn user again"
def failedInspection(self):
dlg = wx.MessageDialog(self,
"The word hello is required before hitting enter or changing focus",
"Where's the hello?!",
wx.OK | wx.CANCEL)
result = dlg.ShowModal()
dlg.Destroy()
if result == wx.ID_OK:
pass
if result == wx.ID_CANCEL:
self.txt.SetLabel("don't forget the 'hello' !")
mySandbox = wx.App()
myFrame = TestFrame()
myFrame.Show()
mySandbox.MainLoop()
exit()
使用的策略是一个标志添加到实例表明,如果它已经被检查,如果文本更改覆盖国旗。
+1
所以本质上,设置“警告已发出标志” –
设置“警告已发出标志” –