matt_t
matt_t

Reputation: 89

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

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)

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?

Thanks for the help.

Upvotes: 1

Views: 4116

Answers (1)

FogleBird
FogleBird

Reputation: 76762

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

Upvotes: 4

Related Questions