如何用CustomTkinter更新倒计时标签?录音器界面卡顿问题
问题解决:CustomTkinter录音器倒计时阻塞GUI的问题
问题根源
- GUI主线程被阻塞:
time.sleep(1)和while循环会占用CustomTkinter的主事件循环,导致按钮失去响应、界面无法实时更新。 - 执行顺序逻辑错误:
sounddevice.rec是非阻塞调用(立即返回),但你的while循环卡住了主线程,直到循环结束才会执行sounddevice.wait()等待录音完成,所以倒计时输出要等录音结束才会显示。
修复后的代码
from customtkinter import * import sounddevice from scipy.io.wavfile import write recorder = CTk() info = CTkLabel(recorder, text="Enter the duration of recording", font=("fb agency", 30)) info.pack() seconds = CTkEntry(recorder, placeholder_text="Enter:") seconds.pack() remaining_time = CTkLabel(recorder, text="not recording") remaining_time.pack() def update_countdown(remaining): if remaining > 0: remaining_time.configure(text=f"Remaining: {remaining}s") # 1秒后再次调用自己,实现倒计时 recorder.after(1000, update_countdown, remaining - 1) else: remaining_time.configure(text="Finished!") # 等待录音完成并保存文件 sounddevice.wait() write("recorded voice.wav", 44100, recorded_voice) # 恢复按钮状态(可选) record_btn.configure(state=NORMAL) def record(): global recorded_voice try: duration = int(seconds.get()) if duration <= 0: remaining_time.configure(text="Please enter a positive number") return # 禁用按钮防止重复点击 record_btn.configure(state=DISABLED) fs = 44100 # 开始录音(非阻塞) recorded_voice = sounddevice.rec(duration * fs, samplerate=fs, channels=2) # 启动倒计时 update_countdown(duration) except ValueError: remaining_time.configure(text="Please enter a valid number") record_btn = CTkButton(recorder, text="RECORD", fg_color="red", command=record) record_btn.pack() recorder.mainloop()
关键修改点
- 用CustomTkinter的
after()方法替代while+time.sleep:after()会在指定时间后将任务加入事件队列,不会阻塞主线程,保证GUI能正常响应和更新。 - 实时更新倒计时标签:把倒计时显示在界面的
remaining_time标签上,替代控制台print,提升用户体验。 - 禁用录音按钮:防止用户在录音过程中重复点击,避免逻辑混乱。
- 错误处理:增加对输入非数字、负数的判断,提升程序健壮性。
内容的提问来源于stack exchange,提问作者taha farzaneh
相关产品推荐
相关产品推荐

