我正在使用python 3和pyqt5创建一个简单的计时器,一旦完成就会响铃。对于计时器,我刚刚创建了一个休眠一秒的循环。根据我的理解,我需要使用线程来使用循环并让循环更新UI而不会冻结直到循环完成。
我遇到的问题是一旦循环完成,我希望我的函数调用另一个在不同线程中的类。我已经尝试过使用QThread和线程,似乎无法解决如何使循环调用从不同的线程调用类。
import sys, time, threading
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtMultimedia import QSound
# setting up the UI
class Ui_Form(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setupUi(self)
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(303, 227)
self.setWorkTxt = QtWidgets.QPlainTextEdit(Form)
self.setWorkTxt.setGeometry(QtCore.QRect(10, 150, 141, 31))
self.setWorkTxt.setObjectName("setWorkTxt")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(10, 190, 141, 27))
self.pushButton.setObjectName("pushButton")
self.countDownTimer = QtWidgets.QLCDNumber(Form)
self.countDownTimer.setGeometry(QtCore.QRect(13, 52, 281, 91))
self.countDownTimer.setProperty("intValue", 0)
self.countDownTimer.setObjectName("countDownTimer")
self.retranslateUi(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Timer"))
self.setWorkTxt.setPlainText(_translate("Form", "enter time"))
self.pushButton.setText(_translate("Form", "Start"))
self.pushButton.clicked.connect(self.start)
# this function creates a new thread and starts the timer
def start(self):
t = threading.Thread(target=self.timer, args=( ))
t.start()
# timer function
def timer(self):
num = int(self.setWorkTxt.toPlainText())
for i in range (1, num + 1):
self.countDownTimer.display(i)
time.sleep(1)
audio.alarm() # this is where I want to call the class from the parent thread
# This is the alarm that I want to sound once the timer is finished
class audio(QSound):
def alarm():
QSound.play("alarm.wav")
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = Ui_Form()
ex.show()
sys.exit(app.exec_())
我是python和Qt的新手,所以如果我的一些术语错了或错过了一些简单的话我会道歉。