简体   繁体   中英

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!

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!

You're calling self.removeError and then you're using the result as target .

So instead of:

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

you have to do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM