wxPython: Threading GUI --> Using Custom Event Handler

后端 未结 3 1157
孤街浪徒
孤街浪徒 2021-02-06 18:41

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

3条回答
  •  我在风中等你
    2021-02-06 19:39

    You can define events like this:

    from wx.lib.newevent import NewEvent
    
    ResultEvent, EVT_RESULT = NewEvent()
    

    You post the event like this:

    wx.PostEvent(handler, ResultEvent(data=data))
    

    Bind it like this:

    def OnResult(event):
        event.data
    
    handler.Bind(EVT_RESULT, OnResult)
    

    But if you just need to make a call from a non-main thread in the main thread you can use wx.CallAfter, here is an example.

    Custom events are useful when you don't want to hard code who is responsible for what (see the observer design pattern). For example, lets say you have a main window and a couple of child windows. Suppose that some of the child windows need to be refreshed when a certain change occurs in the main window. The main window could directly refresh those child windows in such a case but a more elegant approach would be to define a custom event and have the main window post it to itself (and not bother who needs to react to it). Then the children that need to react to that event can do it them selves by binding to it (and if there is more than one it is important that they call event.Skip() so that all of the bound methods get called).

提交回复
热议问题