调用app.MainLoop()后更新wxPython进度栏 [英] Updating a wxPython progress bar after calling app.MainLoop()

查看:854
本文介绍了调用app.MainLoop()后更新wxPython进度栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个执行计算的python脚本,并且为弹出的wxPython进度栏创建了一个类.目前,我有:

I have a python script that performs a calculation, and I have created a class for a pop-up wxPython progress bar. Currently I have:

app=wx.App()
progress = ProgressBar()
app.MainLoop()

for i in xrange(len(toBeAnalysed)):
    analyse(toBeAnalysed[i])
    progress.update(i/len(toBeAnalysed)*100)

现在,由于明显的原因,该示例不起作用.有什么方法可以在不同的线程中运行app.MainLoop(),但是在计算完成后仍能传达进度(和它的.update())?

Now, this example doesn't work for obvious reasons. Is there any way I can run the app.MainLoop() in a different thread but still communicate the progress (and .update() it) as the calculations are completed?

感谢您的帮助.

推荐答案

您应在后台线程中运行逻辑,并使用wx.CallAfter定期更新GUI. CallAfter将在GUI线程上调用提供的函数,因此可以安全地进行GUI调用.

You should run your logic in a background thread and use wx.CallAfter to periodically update the GUI. CallAfter will invoke the provided function on the GUI thread, so it is safe to make GUI calls.

import wx
import threading
import time

def do_stuff(dialog): # put your logic here
    for i in range(101):
        wx.CallAfter(dialog.Update, i)
        time.sleep(0.1)
    wx.CallAfter(dialog.Destroy)

def start(func, *args): # helper method to run a function in another thread
    thread = threading.Thread(target=func, args=args)
    thread.setDaemon(True)
    thread.start()

def main():
    app = wx.PySimpleApp()
    dialog = wx.ProgressDialog('Doing Stuff', 'Please wait...')
    start(do_stuff, dialog)
    dialog.ShowModal()
    app.MainLoop()

if __name__ == '__main__':
    main()

这篇关于调用app.MainLoop()后更新wxPython进度栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆