I have a countdown in tkinter made with a label. the function receives an amount of seconds and starts a countdown to zero. When finished, an alarm sounds.
Problem: The alarm sounds at the correct time but the countdown stays at 1 second for a few more seconds before dropping to 0. How could I correct this?
def countdown(self, segundos):
self.guitimer['text'] = f'00:{segundos}'
if segundos > 0:
self.after(1000, self.countdown, segundos-1)
else:
play(AudioSegment.from_wav("assets/sounds/notification.wav"))
CodePudding user response:
I have finally managed to correct it adding an elif for when segundos is 0 and waiting 1 millisecond more to play the sound.
def countdown(self, segundos):
if segundos > 0:
self.guitimer['text'] = f'00:{segundos}'
self.after(1000, self.countdown, segundos-1)
elif segundos == 0:
self.guitimer['text'] = f'00:{segundos}'
self.after(1, self.countdown, segundos - 1)
print('Production time is finished. Extending production time')
else:
play(AudioSegment.from_wav("assets/sounds/notification.wav"))
CodePudding user response:
You can either force update the label before playing the sound:
def countdown(self, segundos):
self.guitimer['text'] = f'00:{segundos}'
if segundos > 0:
self.after(1000, self.countdown, segundos-1)
else:
self.guitimer.update_idletasks() # update the label
play(AudioSegment.from_wav("assets/sounds/notification.wav"))
or use after()
to execute play(...)
:
def countdown(self, segundos):
self.guitimer['text'] = f'00:{segundos}'
if segundos > 0:
self.after(1000, self.countdown, segundos-1)
else:
self.after(1, play, AudioSegment.from_wav("assets/sounds/notification.wav"))