初学者提问:如何实现中断循环
各位大佬,先声明,我并非从事编程工作者,也没有学过几天python,到这里求助纯粹是不得已,娃学校布置的任务,需要python写个小程序。
网上搜罗了半天,实在是搞不定。问的问题对各位来说简单至极,但行外人真实两眼一抹黑,麻烦各位大佬帮忙,十万火急。拜托拜托。
事情是这样的,需要写一个倒计时提醒的小程序,实现倒计时结束后语音循环播放提醒的功能。捯饬了半天,能倒计时了,也能播报了,但是关闭按钮却不起作用,像死机了一样结束不了程序。麻烦哪位大佬帮忙给改一下,实现播报过程中,按关闭按钮或者键盘上按个ESC键就能停止播报的功能。不胜感激。下面把编凑的程序贴出来,外行瞎编的,大伙别笑话。
import tkinter as tk
import time
import pyttsx3
import Winfo
def start_countdown():
duration = int(time_entry.get())
text = text_entry.get()
tts_engine = pyttsx3.init()
tts_engine.setProperty('rate', 150) # 设置语速
while duration >= 0:
if duration == 0:
tts_engine.say(text)
tts_engine.runAndWait()
else:
mins, secs = divmod(duration, 60)
timer_text.set(f"{mins:02d}:{secs:02d}")
time.sleep(1)
duration -= 1
def stop_speaking():
tts_engine.stop()
window.destroy()
创建主窗口
window = tk.Tk()
window.title(“倒计时对话框”)
创建标签和输入框
time_label = tk.Label(window, text=”时间(秒):”)
time_label.pack()
time_entry = tk.Entry(window)
time_entry.pack()
text_label = tk.Label(window, text=”文本:”)
text_label.pack()
text_entry = tk.Entry(window)
text_entry.pack()
timer_text = tk.StringVar()
timer_text.set(“00:00”)
timer_label = tk.Label(window, textvariable=timer_text)
timer_label.pack()
创建开始按钮和停止按钮
start_button = tk.Button(window, text=”开始”, command=start_countdown)
start_button.pack()
stop_button = tk.Button(window, text=”停止”, command=window.destroy)
stop_button.pack()
运行主循环
window.mainloop()
主要是duration为0时, 不再执行
duration -= 1
.@Jason990420 最近忙本职工作,没能及时来看大佬回复。很是抱歉。试了更新后的代码,终于实现需要的功能了!!万分感谢!! 但是试着用 Pyinstaller 打包成.exe,总是执行不了,看了报错信息,提示 No module named pyttsx3。也去搜了一些解决方案,打包时导入缺少的库等方法,都是无效。不知是什么原因。是我编译环境的问题吗?大佬闲暇时光给试试看吧
I got nothing wrong when
and execute fine, so nothing for you to debug.
学校布置的任务不应该是由学生来完成的吗