Search code examples
pythonmultithreadingtimerpython-multithreading

Running time.sleep() on another thread freezes Tkinter program


So I am trying to run time.sleep() on another thread, but the my entire program still freezes upon calling the function. I call it using a button. This is to create an error, and then wait a couple seconds to remove the error. Not sure what else to do here.

import threading, time

class Block():    
    def createError(self, text):
        background.itemconfig(errorText, text=text, state=NORMAL, font="Neoteric 11 bold")
        background.itemconfig(errorBG, state=NORMAL)

        # Mainly this part to worry about
        t = threading.Thread(target=self.removeError())
        t.start()
        print("Function called") # Only prints AFTER 5 seconds, even though removeError() should be running on another thread

    def removeError(self):
        time.sleep(5)
        background.itemconfig(errorText, text="", state=HIDDEN)
        background.itemconfig(errorBG, state=HIDDEN)

# Tkinter stuff here to create button and run createError()

Any ideas would be awesome!


Solution

  • I figured it out. All that I had to do was use a different function inside threading.

    Swap out:

    t = threading.Thread(target=self.removeError())
    t.start()
    

    To:

    threading._start_new_thread(self.removeError, ())
    

    And that's it. Works like a charm!