【发布时间】:2020-04-13 07:59:17
【问题描述】:
我在 qtdesigner 中设计了一个表单。它有“开”和“关”按钮。开启按钮应该开始闪烁 LED 并且关闭按钮应该停止它。所以,如果 time.sleep 持续时间很短没有问题,但是当我写 10 秒睡眠时,当我点击关闭按钮时它不会立即停止。程序等待 10 秒以停止 LED 闪烁。那么time.sleep怎么打断呢?
import time
import threading
import RPi.GPIO as GPIO
import sys
from time import sleep
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication, QLabel
from PyQt5 import QtCore, QtGui, QtWidgets
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
switch = True
def blink(self):
def run():
while (switch == True):
print('BLINK...BLINK...')
GPIO.output(17, GPIO.HIGH)
time.sleep(10.0)
GPIO.output(17, GPIO.LOW)
time.sleep(10.0)
if switch == False:
break
thread = threading.Thread(target=run)
thread.start()
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 300)
self.pshbttn1 = QtWidgets.QPushButton(Form)
self.pshbttn1.setGeometry(QtCore.QRect(60, 170, 125, 50))
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.pshbttn1.setFont(font)
self.pshbttn1.setObjectName("pshbttn1")
self.pshbttn1.clicked.connect(self.switchon)
self.pshbttn2 = QtWidgets.QPushButton(Form)
self.pshbttn2.setGeometry(QtCore.QRect(220, 170, 125, 50))
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.pshbttn2.setFont(font)
self.pshbttn2.setObjectName("pshbttn2")
self.pshbttn2.clicked.connect(self.switchoff)
self.pshbttn3 = QtWidgets.QPushButton(Form)
self.pshbttn3.setGeometry(QtCore.QRect(140, 230, 125, 50))
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.pshbttn3.setFont(font)
self.pshbttn3.setObjectName("pshbttn3")
self.pshbttn3.clicked.connect(app.exit)
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(80, 80, 251, 51))
font = QtGui.QFont()
font.setPointSize(12)
self.label.setFont(font)
self.label.setObjectName("label")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "LED"))
self.pshbttn1.setText(_translate("Form", "ON"))
self.pshbttn2.setText(_translate("Form", "OFF"))
self.pshbttn3.setText(_translate("Form", "EXIT"))
self.label.setText(_translate("Form", "LED\'i açmak için butonları kullanın"))
def switchon(self):
global switch
switch = True
print ('switch on')
blink(self)
def switchoff(self):
print ('switch off')
global switch
switch = False
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Form()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
【问题讨论】:
-
嗨,欢迎来到 OS。我建议简单地使用更短的时间间隔,但请查看此 post 以了解如何在 Python 中中断
time.sleep()。
标签: python multithreading pyqt pyqt5