0

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()
Adam Lozi
  • 5
  • 3

1 Answers1

1

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.

TheLizzard
  • 7,248
  • 2
  • 11
  • 31
  • @CoolCloud This is faster and would use less memory, given that you know how `t % 3` is going to cycle: 0, 1, 2, 0, 1, 2, 0, 1, 2. – TheLizzard Sep 05 '21 at 22:43
  • Ah well, I do not know about memory consumption of this vs list indexing – Delrius Euphoria Sep 05 '21 at 22:44
  • 1
    @CoolCloud This removes the strings from memory after the `.config`. And this would be more practical if you wanted to just wait for some event like a process to finish. You can replace the `t < 12` with any condition. – TheLizzard Sep 05 '21 at 22:47
  • @TheLizzard thank u so much, I was still struggling with the .after method but now I understand it completely with your code – Adam Lozi Sep 05 '21 at 22:51