zhaoqfeng 发表于 2013-1-1 22:37:02

wxPython使用delayedresult进行耗时处理

<div id="cnblogs_post_body">delayedresult使用背景介绍

在进行wxPython GUI画面编程时,如直接在画面主线程进行大量耗时计算处理,就会造成画面假死,不能响应用户输入。
使用wxPython的delayedresult模块,可轻松解决该问题,甚至都不需要了解相关线程处理机制,即可方便的把耗时处理放到单独的线程中,处理结束后把结果返回GUI画面主线程,并调用预先定义的相关处理,进行画面更新等。
为了演示delayedresult的使用情况,先新建一TestWindow框架,doSomeThing()是我们模拟进行大量耗时处理的函数。

<div class="cnblogs_code"> 1 import wx 2 from wx.lib.delayedresult import startWorker 3 import threading 45 class TestWindow(wx.Frame): 6   def __init__(self, title='Test Window'): 7         self.app = wx.App(False) 8         wx.Frame.__init__(self, None, -1, title) 9         panel = wx.Panel(self)10         self.btnBegin = wx.Button(panel, -1, label='Begin')11         self.Bind(wx.EVT_BUTTON, self.handleButton, self.btnBegin)12         self.txtCtrl = wx.TextCtrl(panel, style=wx.TE_READONLY, size=(300, -1))13         vsizer = wx.BoxSizer(wx.VERTICAL)14         vsizer.Add(self.btnBegin, 0, wx.ALL, 5)15         vsizer.Add(self.txtCtrl, 0, wx.ALL, 5)16         panel.SetSizer(vsizer)17         vsizer.SetSizeHints(self)18         self.Show()19 20   #处理Begin按钮事件21   def handleButton(self, event):22         self.workFunction()23 24   #开始执行耗时处理,有继承类实现25   def workFunction(self, *args, **kwargs):26         print'In workFunction(), Thread=', threading.currentThread().name27         print '\t*args:', args28         print '\t**kwargs:', kwargs29         30         self.btnBegin.Enable(False)31 32   #耗时处理处理完成后,调用该函数执行画面更新显示,由继承类实现33   def consumer(self, delayedResult, *args, **kwargs):34         print 'In consumer(), Thread=', threading.currentThread().name35         print '\tdelayedResult:', delayedResult36         print '\t*args:', args37         print '\t**kwargs:', kwargs38 39         self.btnBegin.Enable(True)40 41   #模拟进行耗时处理并返回处理结果,给继承类使用42   def doSomeThing(self, *args, **kwargs):43         print'In doSomeThing(), Thread=', threading.currentThread().name44         print '\t*args:', args45         print '\t**kwargs:', kwargs46         47         count = 048         while count < 10**8:49             count += 150             51         return count
页: [1]
查看完整版本: wxPython使用delayedresult进行耗时处理