设计一个图形用户界面(GUI)的定时器程序的python代码要求: 1. 可以动态显示时间 2. 到了某一时间如10:10,自动语音提醒“大家好,准备上课”
时间: 2024-05-03 17:21:57 浏览: 140
以下是基于Python的Tkinter库编写的简单GUI定时器程序代码:
```python
import tkinter as tk
import time
import winsound
import speech_recognition as sr
class Timer:
def __init__(self, master):
self.master = master
master.title("定时器")
self.label = tk.Label(master, font=('Helvetica', 48), text="")
self.label.pack()
self.start_button = tk.Button(master, text="开始", command=self.start_timer)
self.start_button.pack(side="left")
self.stop_button = tk.Button(master, text="停止", command=self.stop_timer, state="disabled")
self.stop_button.pack(side="left")
self.reset_button = tk.Button(master, text="重置", command=self.reset_timer, state="disabled")
self.reset_button.pack(side="left")
self.is_running = False
self.is_reset = False
self.duration = 0
def start_timer(self):
if not self.is_running:
self.is_running = True
self.is_reset = False
self.start_button.config(state="disabled")
self.stop_button.config(state="normal")
self.reset_button.config(state="disabled")
self.countdown(self.duration)
def stop_timer(self):
if self.is_running:
self.is_running = False
self.is_reset = False
self.start_button.config(state="normal")
self.stop_button.config(state="disabled")
self.reset_button.config(state="normal")
def reset_timer(self):
self.is_reset = True
self.stop_timer()
self.duration = 0
self.label.config(text="00:00:00")
def countdown(self, duration):
while self.is_running and duration >= 0:
mins, secs = divmod(duration, 60)
hours, mins = divmod(mins, 60)
self.label.config(text="{:02d}:{:02d}:{:02d}".format(hours, mins, secs))
if duration == 600:
self.speech()
time.sleep(1)
duration -= 1
if not self.is_reset:
self.label.config(text="时间到!")
winsound.Beep(800, 1000)
self.reset_timer()
def speech(self):
r = sr.Recognizer()
with sr.Microphone() as source:
print("请说话:")
audio = r.listen(source)
try:
text = r.recognize_google(audio, language="zh-CN")
if "上课" in text:
winsound.Beep(500, 500)
print("大家好,准备上课")
except sr.UnknownValueError:
pass
root = tk.Tk()
timer = Timer(root)
root.mainloop()
```
在这个程序中,我们使用了Python的Tkinter库来创建GUI界面,包括一个标签用于显示时间、三个按钮用于开始、停止和重置计时器。计时器本身是通过一个循环不断更新时间显示,并在达到特定时间时触发语音提醒的。在语音提醒中,我们使用了Python的SpeechRecognition库来实现语音识别,并使用Windows系统自带的Beep声音来进行提示。
阅读全文