wxPython - 防止相同的警告对话框出现两次

wxPython - Prevent the same warning dialog from appearing twice

我有一个 textctrl 接受用户输入。我想在用户输入文本后检查它是否也在预定义的单词列表中。当 textctrl 失去焦点时,我可以进行此检查。我还可以将其设置为检查何时按下回车键。但是,如果我同时执行这两项操作,输入将被检查两次(不是什么大问题,但不是必需的)。如果输入不正确(单词不在列表中),则会弹出 2 个错误对话框。这并不理想。最好的解决方法是什么?

编辑:如果我不清楚,如果输入不正确并按下 Enter,则会弹出 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()

使用的策略是向实例添加一个标志以指示它是否已被检查并在文本更改时覆盖该标志。