darthchild
darthchild

Reputation: 21

Tkinter code for a Timer is crashing the app (python)

I am creating a timer for my quiz app and I decided to try it out first in a separate program, however when I run the following code and press the 'start timer' button the app simply stops responding and I am forced to close it through the task manager

from tkinter import *
import time

root=Tk()
root.geometry('{}x{}'.format(300,200))

lb=Label(root,text='')
lb.pack()

def func(h,m,s):

    lb.config(text=str(h)+':'+str(m)+':'+str(s))
    time.sleep(1)
    s+=1

    func(h,m,s)
    if s==59:
        m=1
        s=0

bt=Button(root,text='start timer',command=lambda:func(0,0,0))
bt.pack()

root.mainloop()

Upvotes: 1

Views: 79

Answers (1)

Henry
Henry

Reputation: 3944

You need to use root.after instead of time.sleep. Here's another answer about making a timer. This is what it looks like applied to your code:

from tkinter import *
import time

root=Tk()
root.geometry('{}x{}'.format(300,200))

lb=Label(root,text='')
lb.pack()

def func(h,m,s):

    lb.config(text=str(h)+':'+str(m)+':'+str(s))
    s+=1
    if s==59:
        m=1
        s=0
    root.after(1000, lambda: func(h,m,s))

bt=Button(root,text='start timer',command=lambda:func(0,0,0))
bt.pack()

root.mainloop()

Upvotes: 2

Related Questions