Search code examples
pythonpython-3.xuser-interfacetkintertkinter-text

Change a tkinter label text every fragment of time


I want to simulate loading on my GUI app but I can't. I'm trying to do this by changing a label text at the bottom of the root through intervals of time, as you can see in my simple code. I want it to work like this:

  • The label text is "Please wait" at first.
  • After 0.5s, it will change to "Please wait." then "Please wait..", "Please wait..." and then the process is on repeat until reaching a specific amount of seconds of waiting.

The problem with my code is that the sleep method (time module) that I used repeatedly will freeze the program until reaching the time limit, which means that "window.mainloop" will not be executed until the end of the loop. And it will only display the last label text value accessed. here is my code:

#

from tkinter import *
import time

window=Tk()

#windowinfo
window.geometry("1080x720")
window.title("")
window.config(bg="#00FFFF")
lrd=PhotoImage(file="C:/Users/hp/OneDrive/Desktop/hhh.png")
ver=Label(window,image=lrd,bd=10,relief=RIDGE)
ver.pack(expand=YES)
wait=Label(window,text="Please wait")
wait.pack(side=BOTTOM)
t=0
while t<4:
    wait.config(text="Please wait.")
    time.sleep(0.5)
    t+=1
    wait.config(text="Please wait..")
    time.sleep(0.5)
    t+=1
    wait.config(text="Please wait...")
    time.sleep(0.5)
    t+=1
#F8D210
#window display
window.mainloop()

Solution

  • Try this:

    import tkinter as tk
    
    window = tk.Tk()
    window.geometry("200x200")
    
    wait = tk.Label(window, text="Please wait")
    wait.pack()
    
    def loop(t=0):
        if t < 12:
            # Change the Label's text
            wait.config(text="Please wait" + "." * (t % 3 + 1))
            # Schedule a call to `loop` in 500 milliseconds with t+1 as a parameter
            window.after(500, loop, t+1)
    
    # Start the loop
    loop()
    
    window.mainloop()
    

    It uses a .after loop. It calls loop every 500 milliseconds while incrementing t.

    The t % 3 cycles between 0, 1, 2 repeatedly. I just added one to all of them to make it: 1, 2, 3, 1, 2, 3, 1, 2, 3.