1

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()
4
  • Do not use time.sleep with tkinter. Use root.after instead. See here for more information. Commented Mar 18, 2021 at 19:07
  • @Henry didn't help Commented Mar 18, 2021 at 19:26
  • What did you try? Commented Mar 18, 2021 at 19:28
  • i replaced time.sleep(1) with root.after(1000, func1) and I put s+=1 in func1 Commented Mar 18, 2021 at 19:32

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.