我怎样才能让这个 tkinter 计时器在响铃之前达到 0?

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

我在用标签制作的 tkinter 中有一个倒计时。该函数接收秒数并开始倒计时到零。完成后,会响起警报。

问题:闹钟在正确的时间响起,但倒计时在 1 秒停留了几秒钟,然后下降到 0。我该如何纠正这个问题?

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

我终于设法更正了它,在 segundos 为 0 时添加了一个 elif,并等待 1 毫秒以上来播放声音。

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

您可以在播放声音之前强制更新标签:

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

或使用after()执行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"))