Is there a way to make the countdown timer run without stopping the whole program?

Viewed 57
import datetime
from datetime import time, datetime
from time import strftime
from tkinter import *
import time as t

def submit():

   try:

       temp = int(countHour.get())*3600 + int(countMinute.get())*60 + int(countSecond.get())

   except:

       print("Please input the right value")

   while temp >-1:

       mins,secs = divmod(temp,60)
 
       hours=0
       if mins >60:
            
           hours, mins = divmod(mins, 60)
        
       
       countHour.set("{:02d}".format(hours))
       countMinute.set("{:02d}".format(mins))
       countSecond.set("{:02d}".format(secs))
       countDownLabel.config(text = countHour.get() + ':' + countMinute.get() + ':' + countSecond.get())
       
       countDown.update()
       countDown.after(100000, submit)
       
       if (temp == 0):
           print('done')
        
       temp -= 1

countDownTitle = Label(countDown, text='Countdown Timer', bg='white', ).pack(fill='x')

countDownBtn = Button(countDown, height=2, width=10, text='Clock', bg='white', command=lambda: showFrame(clockFace)).place(x=50, y=425)

countDownLabel = Label(countDown, bg='black',height = 2, width=8, font=('calibri', 50, 'bold'), fg='white')

timerBtn3 = Button(countDown, height=2, width=10, text='Timer', bg='white', command=lambda: showFrame(timerFace)).place(x=400, y=425)

countDownBtn=Button(countDown, height=2, width=10, text='Countdown', bg='white', command=lambda: showFrame(countDown)).place(x=800, y=425)

trying to make this code run inside a program with a clock and a timer. main solutions I've found for a countdown was to use time.sleep but if I do then the whole application sleeps and I jsut want the countdown to work normally, so I've tried using the .after() function to see if it works and if its less than 10 000 than the countdown stops and trips out before it finishes. I have been trying to just make the timer work for a while now and it goes down now but runs super fast at milliseconds as opposed to just seconds.

TL;DR is there a way I can make the countdown timer run normally without having to use time.sleep so the whole application doesnt freeze every second?

1 Answers

Try this:

startTime = time.time()
while temp + startTime < time.time():
    # update display text
    # use temp - (time.time() - startTime) for left time
Related