Threads - for things that take a long time...


Looping is great for regularly updating the GUI, but if you want to call a function that might take a long time (such as downloading a file) you need to use a thread.

Running your functions in threads allows the main GUI loop to keep running, so that the GUI won't hang.

Threads don't always work nicely with GUIs, so your thread shouldn't try to change the GUI, instead you will need to put any GUI updates in a Queue.

downloadCount = 0

def downloader():
    global downloadCount
    # it's fine to put loops in threads
    for i in range(5):
        # update the GUI through the GUI queue
        app.queueFunction(app.setLabel, "l1", "Starting download " + str(downloadCount))
        # this takes a long time
        downloadFile("file" + str(downloadCount) + ".dat")
        # update the GUI through the GUI queue
        app.queueFunction(app.setLabel, "l1", "Finished download " + str(downloadCount))
        # it's fine to put sleeps in threads
        time.sleep(1)

# put the downloader function in its own thread
app.thread(downloader)