wxPython wx.CallAfter - how do I get it to execute immediately?

前端 未结 2 1898
悲&欢浪女
悲&欢浪女 2021-01-23 01:13

When I execute a function with wx.CallAfter, inside it a variable is set. I want to be able to get the value of that variable on the next line, however CallAfter seems to execut

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-23 01:47

    As you've guessed wx.CallAfter adds the call info to a queue (the pending event queue, which is processed in the GUI thread the next time the event queue is emptied) and then returns immediately. In other words, it is intended to be a "fire and forget" function call.

    If you need to get the result of that called function there are a few approaches that can be taken. One is the delayed result pattern, where basically you get a result object that will receive the result of the function call after it has been called, and the calling code can get a notification when that happens. There is an implementation of this in wx.lib.delayedresult and probably other implementations of this pattern can be found in various places. The nice thing about this approach is that the calling thread doesn't have to stop and wait for the result and can continue processing other things if desired.

    Another approach that is quite nice in my opinion is wxAnyThread, which can be found at https://pypi.python.org/pypi/wxAnyThread/. This module provides a decorator that allows methods to be called from any thread like a normal function call, but when called from something other than the GUI thread it will use wx.CallAfter-like processing to have the function called in the UI thread, and then wait for the result and will return it to the caller when it is received. So although the calling thread is blocked while the UI events are processed and the function is called, it is much simpler to use and reduces complexity on the calling side.

提交回复
热议问题