gpt4 book ai didi

python - 如何从 PyQt 正确执行多处理?

转载 作者:太空狗 更新时间:2023-10-30 01:05:06 25 4
gpt4 key购买 nike

我创建了一个按钮并尝试在单击按钮时运行多处理,

但是 UI 被阻塞了。我希望进程在后台运行。

我该如何解决?

from PySide2 import QtCore,QtGui,QtWidgets
import sys
import multiprocessing
from threading import Timer
class TTT(multiprocessing.Process):
def __init__(self):
super(TTT, self).__init__()
self.daemon = True
def run(self):
while True:
t = Timer(5, self.doSomething)
t.start()
t.join()

def doSomething(self):
try:
print('123')
except Exception as e:
print(e)

class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
btn = QtWidgets.QPushButton('run process')
btn.clicked.connect(self.create_process)
self.setCentralWidget(btn)

def create_process(self):
QtWidgets.QMessageBox.information(self,'hhh','hhh')
t = TTT()
t.start()
t.join()

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

最佳答案

Bendegúz Szatmári 已经回答了主要问题。

我只是想让你知道,在大多数情况下,使用 Process 并不是最好的主意。不同的进程不与您的程序共享内存。你不能像不同的线程那样容易地控制它们。

这是一个简单的例子,你可以开始结束停止不同的线程。

from PyQt5 import QtWidgets
from PyQt5.QtCore import *
import sys
import time


class TTT(QThread):
def __init__(self):
super(TTT, self).__init__()
self.quit_flag = False

def run(self):
while True:
if not self.quit_flag:
self.doSomething()
time.sleep(1)
else:
break

self.quit()
self.wait()

def doSomething(self):
print('123')


class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.btn = QtWidgets.QPushButton('run process')
self.btn.clicked.connect(self.create_process)
self.setCentralWidget(self.btn)

def create_process(self):
if self.btn.text() == "run process":
print("Started")
self.btn.setText("stop process")
self.t = TTT()
self.t.start()
else:
self.t.quit_flag = True
print("Stop sent")
self.t.wait()
print("Stopped")
self.btn.setText("run process")


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

关于python - 如何从 PyQt 正确执行多处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47649159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com