开发者

Updating a wxPython progress bar after calling app.MainLoop()

开发者 https://www.devze.com 2023-03-25 01:52 出处:网络
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:

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)

N开发者_如何学运维ow, 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?

Thanks for the help.


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()
0

精彩评论

暂无评论...
验证码 换一张
取 消