How can I change a label text after a specific time without after() function in tkinter python?
Question:
The code i tried to accomplish my result:
from tkinter import*
import time
root=Tk()
lyrics=StringVar()
lyrics.set("unleash")
l=Label(root,textvariable=lyrics)
l.pack()
def change_text():
lyrics.set("you!!")
print('ses')
time.sleep(6.9)
change_text()
mainloop()
The problems in this are like the window is displayed after 10 sec. If I shift the mainloop()
before the time.sleep()
function the time.sleep()
executes after the app is closed. The reason is simple that I didn’t use after() function because the after()
function doesn’t accepts the sec value in decimal.
Any help is appreciated
Answers:
The after()
function takes the delay argument in milliseconds, where you would pass 6900
instead of 6.9
. See: https://www.tcl.tk/man/tcl8.4/TclCmd/after.html
The problem is that mainloop()
blocks further execution. You can always use a background thread:
def bg_thread():
time.sleep(6.9)
change_text()
thread = threading.Thread(target=bg_thread)
thread.start()
mainloop()
Threading, of course, brings with it a whole host of challenges. It’s a good idea to make sure you know what you’re doing when working with threads.
See also:
https://docs.python.org/3/library/threading.html#threading.Thread
import time
def update_label():
///update label text here
label.config(text="New label text")
/// wait for 5 seconds before updating the label
time.sleep(5)
update_label()
The code i tried to accomplish my result:
from tkinter import* import time root=Tk() lyrics=StringVar() lyrics.set("unleash") l=Label(root,textvariable=lyrics) l.pack() def change_text(): lyrics.set("you!!") print('ses') time.sleep(6.9) change_text() mainloop()
The problems in this are like the window is displayed after 10 sec. If I shift the mainloop()
before the time.sleep()
function the time.sleep()
executes after the app is closed. The reason is simple that I didn’t use after() function because the after()
function doesn’t accepts the sec value in decimal.
Any help is appreciated
The after()
function takes the delay argument in milliseconds, where you would pass 6900
instead of 6.9
. See: https://www.tcl.tk/man/tcl8.4/TclCmd/after.html
The problem is that mainloop()
blocks further execution. You can always use a background thread:
def bg_thread():
time.sleep(6.9)
change_text()
thread = threading.Thread(target=bg_thread)
thread.start()
mainloop()
Threading, of course, brings with it a whole host of challenges. It’s a good idea to make sure you know what you’re doing when working with threads.
See also:
https://docs.python.org/3/library/threading.html#threading.Thread
import time
def update_label():
///update label text here
label.config(text="New label text")
/// wait for 5 seconds before updating the label
time.sleep(5)
update_label()