Home > Back-end >  Why time.sleep doesn't work in this function?
Why time.sleep doesn't work in this function?

Time:04-17

i have this simple program just for understand and when i press "0" i enter in the "def func", it should change the background of the button into red, than wait 3 second and then print "hello", but when i run it and i press "0" the program first sleeps 3 seconds, and then change the background and then print "hello", why?? It should first change the background and then execute the other lines, you could 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()

But if i try to put this code inside the function it works executing first the "Print("Hello") line and the the rest of the code:

def func(event): print ("Hello") time.sleep(3) print ("How are you")

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