Search code examples
pythonuser-interfacetkintercountdown

How can I make this tkinter timer get to 0 before it rings?


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"))

Solution

  • 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"))