Skip to content Skip to sidebar Skip to footer

Python+tkinter, How To Run In Background Independant Of Tk Frontend?

I'm a tkinter noob. What would be the preferred way to run a long-running process in the background, separate from my tkinter popup(form?)? I've read different things about multith

Solution 1:

Joran Beasley has the right answer, but way over-complicated things.

Here's the simple version:

class Worker(threading.Thread):
    def run(self):
        # long process goes here

w = Worker()
w.start()
tkMessageBox.showinfo("Work Started", "OK started working")
w.join()
tkMessageBox.showinfo("Work Complete", "OK Done")

Edit: here's a working example of it:

import threading
import time
import tkMessageBox
import Tkinter as tk
root = tk.Tk()
root.withdraw()

classWorker(threading.Thread):
    defrun(self):
        # long process goes here
        time.sleep(10)

w = Worker()
w.start()
tkMessageBox.showinfo("Work Started", "OK started working")
root.update()
w.join()
tkMessageBox.showinfo("Work Complete", "OK Done")

Solution 2:

theading is simpler since you can share object state

classWorker:
    finished = Falsedefdo_work(self):
       os.system("...")
       self.finished=Truedefstart(self):
        self.th = threading.Thread(target=self.do_work)
        self.th.start()

w = Worker()
w.start()
tkMessageBox.showinfo("Work Started", "OK started working")
whilenot w.finished:
    time.sleep(0.5)
tkMessageBox.showinfo("Work Complete", "OK Done")

Post a Comment for "Python+tkinter, How To Run In Background Independant Of Tk Frontend?"