pyqt中通过两个按钮利用线程分别启动功能包,并利用一个按钮结束线程(python)(需要具体示例
时间: 2024-06-10 20:09:00 浏览: 96
)很高兴回答你的问题!下面是一个例子,通过两个按钮分别启动不同的线程,一个按钮终止所有线程:
```python
import sys
import time
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
from PyQt5.QtCore import QThread, pyqtSignal, pyqtSlot
class Worker(QThread):
finished = pyqtSignal()
def __init__(self, name):
super().__init__()
self.name = name
self.running = False
def run(self):
self.running = True
while self.running:
print(f"{self.name} is running")
time.sleep(1)
self.finished.emit()
def stop(self):
self.running = False
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.btn1 = QPushButton('Start Thread 1')
self.btn2 = QPushButton('Start Thread 2')
self.btnStop = QPushButton('Stop All Threads')
self.btnStop.setEnabled(False)
vbox = QVBoxLayout()
vbox.addWidget(self.btn1)
vbox.addWidget(self.btn2)
vbox.addWidget(self.btnStop)
self.setLayout(vbox)
self.btn1.clicked.connect(lambda: self.startThread("Thread 1"))
self.btn2.clicked.connect(lambda: self.startThread("Thread 2"))
self.btnStop.clicked.connect(self.stopAllThreads)
self.show()
def startThread(self, name):
worker = Worker(name)
worker.finished.connect(worker.deleteLater)
worker.finished.connect(self.threadFinished)
worker.start()
self.btnStop.setEnabled(True)
def threadFinished(self):
if not any(isinstance(w, Worker) for w in self.children()):
self.btnStop.setEnabled(False)
def stopAllThreads(self):
for w in self.children():
if isinstance(w, Worker):
w.stop()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
```
希望这个例子对你有所帮助!如果你有更多的问题,欢迎继续提问。
阅读全文