按下按钮时断开无限循环



我目前开始使用PyQt5并创建了我的第一个GUI。现在我想要一个执行以下操作的程序。当按下按钮"开始"时,执行"功能"n次,直到按下按钮"停止"(想象一下秒表(,如果我再次按下按钮"开始","功能"再次执行,依此类推。

到目前为止,我尝试的是以下内容,这是行不通的,因为我们无法从循环外部更改变量(模型脚本(

class Ui(QtWidgets.QDialog):
def __init__(self):
super(Ui, self).__init__()
uic.loadUi('interfaceScan.ui', self)
self.startScan = self.findChild(QtWidgets.QPushButton, 'startScan') 
self.startScan.clicked.connect(self.startPressed)
self.pauseScan = self.findChild(QtWidgets.QPushButton, 'pauseScan')
self.pauseScan.clicked.connect(self.pausePressed) 
self.show()
def startPressed(self):
global pauseScan
pauseScan = False 
dosomething()
def pausePressed(self):
global pauseScan
pausScan = True
def dosomething(): 
while pauseScan == False: #not needed, but the measurement should be executed periodically until 'pause' is pressed
print('Running') #in the reals program the measurement will be executed here 
time.sleep(4) #between each measurement the program needs to wait a cirtain amount of time ~1h  
app = QtWidgets.QApplication(sys.argv)
window = Ui()
app.exec_()

关于如何解决这个问题的任何想法?我现在相对确定它在使用 while 循环时不起作用,所以我愿意接受有关如何更改它的建议!

此脚本的目的是控制应该运行 1000 个周期的测量设置,但我希望能够在两者之间中断它以更改参数。

正如 OP 在注释中指出的那样,带有 time.sleep(( 的 while 循环仅旨在执行周期性任务,但这会产生问题,因为 time.sleep(( 冻结了 GUI,而是必须使用 QTimer:

from PyQt5 import QtCore, QtWidgets, uic

class Ui(QtWidgets.QDialog):
def __init__(self):
super(Ui, self).__init__()
uic.loadUi("interfaceScan.ui", self)
self.startScan.clicked.connect(self.startPressed)
self.pauseScan.clicked.connect(self.pausePressed)
self.timer = QtCore.QTimer(self, interval=4 * 1000, timeout=dosomething)
@QtCore.pyqtSlot()
def startPressed(self):
QtCore.QTimer.singleShot(0, dosomething)
self.timer.start()
@QtCore.pyqtSlot()
def pausePressed(self):
self.timer.stop()

def dosomething():
print("Running")

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = Ui()
window.show()
sys.exit(app.exec_())

最新更新