Home > Mobile >  Why doesn't time.sleep work in this function?
Why doesn't time.sleep work in this function?

Time:04-18

I have this simple program just for my understanding, and when I press "0" I enter into the "def func", it should change the background of the button to red, then wait 3 seconds and print "hello", but when I run it and I press "0", the program first sleeps 3 seconds, and then changes the background and then prints "hello", why?? It should first change the background and then execute the other lines. You can try copying my code:

import time
from tkinter import *
window = Tk()
window.geometry("500x300")
def func(event):
    button.configure(bg="Red")
    time.sleep(3)
    print("hello")
button= Button(window,text= "Hello", font= ('Helvetica 20 '),width=5,height=1,bg="#008BC7")
window.bind("0", func)
button.pack()

CodePudding user response:

Q. Why did all of this happen?
A. Because all changes happen after the function exit.
Try This: Instead of time.sleep(3) write for a in range(10000): print(a) here you can check the background of button change after the loop and the last line which is print('hello') execute.

Don't use time.sleep() when using tkinter library because there is a method in here call Tk().after(timeInMillisecond,function).

Tk().after() method does not stop the program from running it executes the function after the given time below I use the lambda function instead of the normal function.

import time
from tkinter import *
window = Tk()
window.geometry("500x300")
def func(event):
    button.configure(bg="Red")
    window.after(3000,lambda:print('hello'))# edited
button= Button(window,text= "Hello", font= ('Helvetica 20 '),width=5,height=1,bg="#008BC7")
window.bind("0", func)
button.pack()
window.mainloop()

Instead of lambda function, You can also use the normal function here.

import time
from tkinter import *
window = Tk()
window.geometry("500x300")
def print_hello():
    print('hello')
def func(event):
    button.configure(bg="Red")
    window.after(3000,print_hello) # edited
button= Button(window,text= "Hello", font= ('Helvetica 20 '),width=5,height=1,bg="#008BC7")
window.bind("0", func)
button.pack()
window.mainloop()
  • Related