Working with the results of a thread without blocking tkinter

I have a minimal tkinter program which analyses some data. Some of the datafiles are quite large, so to ensure that the GUI remains responsive I load the data in a new thread.

How can I run analysis on the data once the thread has terminated?

Some example code is below.

import tkinter
from threading import Thread
from time import sleep

result = []

def func(result):
    sleep(10)
    ans = 1
    result.append(ans)

class myApp(tkinter.Tk):
    def __init__(self, parent):
        tkinter.Tk.__init__(self, parent)
        self.grid()

        self.myButton = tkinter.Button(self, text="Press me!", command=self.onButtonPress)
        self.myButton.grid(column=0, row=0)

    def onButtonPress(self):
        thread = Thread(target=func, args=(result,))
        thread.start()

        self.myButton["text"]=result

app = myApp(None)
app.mainloop()

How can I make the button text change only when func returns?

1 answer

  • answered 2017-11-12 21:13 Curly Joe

    multiprocessing has an isalive() function and so you can use Tkinter's after() to query it periodically if you want to switch over