Shatnerz
Shatnerz

Reputation: 2543

wxPython - Prevent the same warning dialog from appearing twice

I have a textctrl accepting user input. I want to check the text after the user enters it to see if it is also in a predefined list of words. I can do this check when the textctrl loses focus. I can also set it to check when the enter key is pressed. However, if I do both, the input is checked twice (not a huge deal, but not necessary). If the input is incorrect (the word is not in the list) then 2 error dialogs pop up. This is not ideal. What is the best way around this?

Edit: In case I wasn't clear, 2 warnings popup if the input is incorrect and Enter is hit. This causes one dialog to appear, which steals focus, causing the second to appear.

Upvotes: 0

Views: 207

Answers (1)

thorr18
thorr18

Reputation: 347

This demo code meets your criteria.
You should be able to test run it in its entirety in a separate file.

    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()

The strategy used was to add a flag to the instance to indicate if it has already been inspected and to overwrite the flag if the text changes.

Upvotes: 1

Related Questions