Search code examples
pythonwxpythonwxwidgets

wxPython Application.DoEvents() equivalent?


Is there an Application.DoEvents() equivalent in wxPython?

I am creating a form, then doing a slow I/O event, and the form is only partially drawn until the event finishes. I'd like to have the form fully drawn before the I/O starts.

I've tried self.Refresh(), but it has no effect.


Solution

  • wx.Yield or wx.SafeYield

    Although you should really use a separate thread to do the I/O and use wx.CallAfter to post updates to the GUI thread.

    I usually use a pattern like this:

    def start_work(self):
        thread = threading.Thread(target=self.do_work, args=(args, go, here))
        thread.setDaemon(True)
        thread.start()
    def do_work(self, args, go, here):
        # do work here
        # wx.CallAfter will call the specified function on the GUI thread
        # and it's safe to call from a separate thread
        wx.CallAfter(self.work_completed, result, args, here)
    def work_completed(self, result, args, here):
        # use result args to update GUI controls here
        self.text.SetLabel(result)
    

    You would call start_work from the GUI, for example on an EVT_BUTTON event to start the work. do_work is run on a separate thread but it cannot do anything GUI related because that has to be done on the GUI thread. So you use wx.CallAfter to run a function on the GUI thread, and you can pass it arguments from the work thread.