I am creating a GUI that needs to have timer starting from 0 and counting up every second until it reaches a limit This is the code I have right now
limit = 10
score = 0
def update():
global score, limit
time.sleep(1)
score += 1
ScoreL.configure(text=score)
if score < limit:
update()
ScoreL = tkinter.Label(window, text = score)
ScoreL.pack()
update()
window.mainloop
Right now this is increasing the score each second but it does not open the GUI until the score reaches the limit. How can I make it so the GUI opens when the score is 0 but will continue to update each second?
time.sleep()
will block tkinter mainloop from updating, so you can only see the result after the score reaches the limit because at that time tkinter mainloop takes back the control.
Use .after()
instead:
import tkinter
window = tkinter.Tk()
limit = 10
score = 0
def update():
global score
score += 1
ScoreL.configure(text=score)
if score < limit:
# schedule next update 1 second later
window.after(1000, update)
ScoreL = tkinter.Label(window, text=score)
ScoreL.pack()
window.after(1000, update) # start the update 1 second later
window.mainloop()