Wednesday, December 16, 2015

Python example of using Thread


It's a simple Python example to run code in background thread, to keep GUI responsive.

#tkinter for Python 3.x
#Tkinter for Python 2.x
 
import tkinter
from threading import Thread
import time
 
def quit():
    global tkTop
    tkTop.destroy()

def doSomething():
    print("Do something")
    for count in range(5):
        time.sleep(1)
        varLabel.set(str(count)) 

def runThread():
    varLabel.set("runThread() called")
    myThread = Thread(target=doSomething)
    myThread.start()
 
tkTop = tkinter.Tk()
tkTop.geometry('300x200')
 
tkButtonQuit = tkinter.Button(
    tkTop,
    text="Quit",
    command=quit)
tkButtonQuit.pack()

tkButtonRunThread = tkinter.Button(
    tkTop,
    text="Do something in another thread",
    command=runThread)
tkButtonRunThread.pack()

tkDummyButton = tkinter.Button(
    tkTop,
    text="Dummy Button")
tkDummyButton.pack()
 
varLabel = tkinter.StringVar()
tkLabel = tkinter.Label(textvariable=varLabel)
tkLabel.pack()
 
tkinter.mainloop()