wxPython: Threading GUI --> Using Custom Event Handler

PPTim picture PPTim · Feb 27, 2010 · Viewed 8.2k times · Source

I am trying to learn how to run a thread off the main GUI app to do my serial port sending/receiving while keeping my GUI alive. My best Googling attempts have landed me at the wxpython wiki on: http://wiki.wxpython.org/LongRunningTasks which provides several examples. I have settled on learning the first example, involving starting a worker thread when the particular button is selected.

I am having trouble understanding the custom-event-definition:

def EVT_RESULT(win, func):
    """Define Result Event."""
    win.Connect(-1, -1, EVT_RESULT_ID, func)

class ResultEvent(wx.PyEvent):
    """Simple event to carry arbitrary result data."""
    def __init__(self, data):
        """Init Result Event."""
        wx.PyEvent.__init__(self)
        self.SetEventType(EVT_RESULT_ID)
        self.data = data

Primarily the

def EVT_RESULT(win, func):
    """Define Result Event."""
    win.Connect(-1, -1, EVT_RESULT_ID, func)

I think EVT_RESULT is placed outside the classes so as to make it call-able by both classes (making it global?)

And.. the main GUI app monitors the thread's progress via:

# Set up event handler for any worker thread results
EVT_RESULT(self,self.OnResult)

I also notice that in a lot of examples, when the writer uses

from wx import *

they simply bind things by

EVT_SOME_NEW_EVENT(self, self.handler)

as opposed to

wx.Bind(EVT_SOME_NEW_EVENT, self.handler)

Which doesn't help me understand it any faster. Thanks,

Answer

DrBloodmoney picture DrBloodmoney · Feb 27, 2010

That's the old style of defining custom events. See the migration guide for more information.

Taken from the migration guide:

If you create your own custom event types and EVT_* functions, and you want to be able to use them with the Bind method above then you should change your EVT_* to be an instance of wx.PyEventBinder instead of a function. For example, if you used to have something like this:

myCustomEventType = wxNewEventType()
def EVT_MY_CUSTOM_EVENT(win, id, func):
    win.Connect(id, -1, myCustomEventType, func)

Change it like so:

myCustomEventType = wx.NewEventType()
EVT_MY_CUSTOM_EVENT = wx.PyEventBinder(myCustomEventType, 1)

Here is another post that I made with a couple of example programs that do exactly what you are looking for.