You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter倒计时程序运行一段时间后有时不发声问题求助

问题排查与解决方案

问题根源

  • 原代码用while循环+time.sleep(1)阻塞了tkinter的主事件循环,导致程序无法及时处理系统音频请求,偶尔出现发声失败。
  • 每次计时结束递归调用OK(),会不断积累函数调用栈,运行数分钟后栈溢出,直接跳过发声逻辑进入下一轮计时。

修复后的代码

import winsound
from tkinter import *

root = Tk()
root.title("50 sec timer")
Second = StringVar()
Second.set("50")
Second_entry = Entry(root, width=3, font=("Comic Sans MS", 40, ""), fg='blue', textvariable=Second)
Second_entry.grid(row=0, column=0, sticky=W+E)

def countdown(temp=50):
    if temp >= 0:
        Second.set("{0:2d}".format(temp))
        if temp == 0:
            winsound.Beep(840, 1200)
            # 计时结束后,延迟1毫秒启动下一轮(给系统处理音频的时间)
            root.after(1, countdown)
        else:
            # 每隔1秒调用自身更新计时
            root.after(1000, countdown, temp - 1)

button = Button(root, text=' countdown', bd='5', font=("Comic Sans MS", 30, ""), fg='blue', command=countdown)
button.grid(row=1, column=0)

root.bind('<space>', lambda e: countdown())
root.mainloop()

修改说明

  • 用tkinter原生的after()方法替代while+sleep,不会阻塞主事件循环,确保程序始终响应系统事件(包括音频播放)。
  • 去掉递归调用,改用after()循环触发计时逻辑,避免函数调用栈溢出。
  • 计时结束发声后,用after(1, countdown)延迟启动下一轮,给系统足够时间处理音频播放,避免冲突。

内容的提问来源于stack exchange,提问作者Vade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 16:38:22