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()
精彩评论