Home > Back-end >  How can I update the label everytime in loop with tkinter configure. Below code only displaying the
How can I update the label everytime in loop with tkinter configure. Below code only displaying the

Time:04-07

from tkinter import *
import time

win = Tk()
def call():
    for i in range(5, 0, -1):
        time.sleep(1)
        l1.configure(text = str(i)   " seconds left")

l1 = Label(win, text = "Timer")
l1.pack()

b1 = Button(win, text = "Click", command = call)
b1.pack()

win.mainloop()

This code is waiting for the 4 seconds and giving the final loop value only

CodePudding user response:

This is a problem with tkinter as we are using the time module I guess, the way I got around is by changing the name of the window here is the code, also you may want to use f strings:

from tkinter import *
import time

win = Tk()
win.geometry('300x400')

def call():
    for i in range(5, 0, -1):
        i -= 1
        time.sleep(1)
        win.title(f'{i} seconds left')

l1 = Label(win, text = "Timer")
l1.pack()

b1 = Button(win, text = "Click", command = call)
b1.pack()

win.mainloop()

CodePudding user response:

from tkinter import *
# import time

win = Tk()
def call():
    for i in range(5, 0, -1):
        win.update()                     # gets updated everytime
        l1.configure(text = str(i)   " seconds left")
        win.after(1000)                  # sleep for a second
   
l1 = Label(win, text = "Timer")
l1.pack()

b1 = Button(win, text = "Click", command = call)
b1.pack()

win.mainloop()

This code worked..

  • Related