我很清楚/熟悉如何处理 LongRunningTasks在 wxPython 中(使用 threading.Thread 工作正常)。但我一直想知道,为什么 wx.Yield() 和它的 sibling 不工作(或者它们应该如何正确使用)。
附上一个(不是这样的)最小示例,使用 4.0.0a2 msw (phoenix) 测试:
from __future__ import print_function
from time import sleep
from datetime import datetime
import wx
def long_running(handler):
for i in range(10):
thetxt = '{0}: {1}'.format(str(datetime.now()), str(i))
sleep(1) # using this as drop-in for something which is blocking
wx.SafeYield()
wx.CallAfter(handler, thetxt)
class tst_frm(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.btn = wx.Button(self, -1, 'Click to Status')
self.btn.Bind(wx.EVT_BUTTON, self.on_btn)
def on_btn(self, evt):
the_txt = '{0}: EVT_BUTTON'.format(str(datetime.now()))
self.update_prog(the_txt)
def update_prog(self, update_txt):
"""Handler for task update (``str``)."""
print(update_txt)
if __name__ == '__main__':
app = wx.App(redirect=False)
frm = tst_frm(None, -1, 'test_long')
frm.Show()
handler = frm
long_running(handler.update_prog)
app.MainLoop()
编辑:发生了什么:
- 处理
wx.CallAfter事件 - 按钮事件已注册,但仅在
long_running完成后才在 GUI 中处理
我的问题:
wx.Yield应该允许处理堆积的事件?- 这个例子能否与
wx.Yield一起工作?如果可以,如何? - 如果不是,请问为什么它不起作用?
请您参考如下方法:
wxpython-users 中的人能够回答问题。有两件事是错误的:
long_running在app.MainLoop()有机会处理事件之前启动。确保long_running在 MainLoop 之后开始wx.Yield()是允许处理 wx 事件循环的正确方法
对此进行修改使其工作:
def long_running(handler):
for i in range(10):
thetxt = '{0}: {1}'.format(str(datetime.now()), str(i))
sleep(1) # using this as drop-in for something which is blocking
wx.CallAfter(handler, thetxt)
wx.Yield()
…
if __name__ == '__main__':
…
wx.CallLater(1500, long_running, handler.update_prog)
app.MainLoop()
