一、代码展示:
import sys
from PyQt6.QtCore import QTimer, QTime
from PyQt6.QtWidgets import QWidget, QApplication, QLabel, QPushButton, QLineEdit
from PyQt6 import uic
from PyQt6.QtTextToSpeech import QTextToSpeech
# 封装一个我的窗口类
class MyWidget(QWidget):
def __init__(self):
super().__init__()
# 通过uic将ui界面加载到程序中来
ui = uic.loadUi("./Form.ui",self)
self.label:QLabel = ui.label
self.pushButton:QPushButton = ui.pushButton
self.lineEdit:QLineEdit = ui.lineEdit
self.label_4:QLabel = ui.label_4
self.timer = QTimer()
self.timer.timeout.connect(self.timeout_slot)
self.timer.start(1000)
self.alarm_timer = QTimer()
self.alarm_timer.timeout.connect(self.stop_alarm)
self.pushButton.clicked.connect(self.pushButton_slot)
self.alarm_time = None
self.alarm_active = False
self.alarm_sounding = False
self.speecher = QTextToSpeech()
def pushButton_slot(self):
if self.pushButton.text() == "启动":
input_time = self.lineEdit.text()
try:
self.alarm_time = QTime.fromString(input_time,"hh:mm:ss")
if self.alarm_time.isValid():
self.pushButton.setText("关闭")
self.alarm_active = True
self.label_4.setText(f"现在是北京时间{input_time}")
else:
self.label_4.setText("输入的时间格式不正确,请使用 hh:mm:ss")
except ValueError:
self.label_4.setText("输入的时间格式不正确,请使用 hh:mm:ss")
else:
if self.alarm_sounding:
self.stop_alarm()
else:
self.pushButton.setText("启动")
self.alarm_active = False
self.label_4.setText("")
def timeout_slot(self):
sys_time = QTime.currentTime()
t = sys_time.toString("hh:mm:ss")
self.label.setText(t)
if self.alarm_active and sys_time>=self.alarm_time and not self.alarm_sounding:
self.alarm_active = False
self.alarm_sounding = True
self.alarm_timer.start(30000)
self.start_alarm()
def start_alarm(self):
def speak_loop():
if self.alarm_sounding:
self.speecher.say(self.label_4.text())
QTimer.singleShot(10000,speak_loop)
speak_loop()
def stop_alarm(self):
self.alarm_timer.stop()
self.alarm_sounding = False
self.pushButton.setText("启动")
self.label_4.setText("")
if __name__ == '__main__':
app = QApplication(sys.argv)
myWidget = MyWidget()
myWidget.show()
sys.exit(app.exec())
二、结果展示:
