i want to animate a label text in tkinter (python). for that purpose, i am using time.sleep() method for updating 1 character in Label widget after a second but it is not updating Label widget instantly rather it is updating label at once at the end of timer. How could i fix this?. Here is my code:-
from tkinter import *
import time
global a
def update(a):
txt = 'Sample Text'
mylabel.configure(text=txt[0:a])
def timer():
global a
a = 0
lenth = len('Sample Text')
start = time.time()
while True:
# Do other stuff, it won't be blocked
time.sleep(0.1)
# When 1 sec or more has elapsed...
if time.time() - start > 1:
start = time.time()
a = a 1
# This will be updated once per second
print("{} counter".format(a))
update(a)
# Count up to the lenth of text, ending loop
if a > lenth:
break
root = Tk()
root.geometry('300x300')
mylabel = Label(root, text="S", font=('Bell', 36, 'bold'))
mylabel.pack(pady=5)
root.after(3000, timer)
root.mainloop()
CodePudding user response:
It is not recommended to use loop and time.sleep()
in the main thread of a tkinter application because it will block the tkinter mainloop()
from updating widgets until the loop exits. That is why you can only see the result after the loop completes.
Use .after()
instead:
import tkinter as tk
root = tk.Tk()
#root.geometry('300x300')
txt = 'Sample Text'
lbl = tk.Label(root, font='Bell 36 bold', width=len(txt))
lbl.pack(pady=5)
def animate_label(text, n=0):
if n < len(text)-1:
# not complete yet, schedule next run one second later
lbl.after(1000, animate_label, text, n 1)
# update the text of the label
lbl['text'] = text[:n 1]
# start the "after loop" one second later
root.after(1000, animate_label, txt)
root.mainloop()