Python 如何在PyQt5中停止线程
我试图寻找解决问题的方法,但我似乎找不到正确的方法,在GUI没有得到“无响应”的情况下停止它 基本上,我是如何启动和停止它的:Python 如何在PyQt5中停止线程,python,python-3.x,pyqt5,Python,Python 3.x,Pyqt5,我试图寻找解决问题的方法,但我似乎找不到正确的方法,在GUI没有得到“无响应”的情况下停止它 基本上,我是如何启动和停止它的: def startTheThread(self): self.check_elements() # Create the new thread. The target function is 'myThread'. The # function we created in the beginning.
def startTheThread(self):
self.check_elements()
# Create the new thread. The target function is 'myThread'. The
# function we created in the beginning.
_email = str(self.lineEdit.text())
_password = str(self.lineEdit_2.text())
captcha_api = str(self.lineEdit_5.text())
print(betburg_email)
print(betburg_password)
print(captcha_api)
print(mode)
self.t = threading.Thread(name = 'myThread', target = myThread, args = (self.theCallbackFunc, _email, _password, captcha_api))
self.t.start()
def stop_client(self):
self.check_elements()
self.t.join()
def theCallbackFunc(self, msg):
print('the thread has sent this message to the GUI:')
print(msg)
print('---------')
class Communicate(QtCore.QObject):
myGUI_signal = QtCore.pyqtSignal(str)
def myThread(callbackFunc, betburg_email, betburg_password, captcha_api):
# Setup the signal-slot mechanism.
mySrc = Communicate()
mySrc.myGUI_signal.connect(callbackFunc)
# Endless loop. You typically want the thread
# to run forever.
while(True):
# Do something useful here.
client_run(betburg_email, betburg_password, captcha_api)
msgForGui = 'Thread running...'
mySrc.myGUI_signal.emit(msgForGui)
我尝试启动另一个线程来处理关闭,但也不起作用。我正在使用
threading.threading()
,我尝试了SO上的可用功能,并且.join()
是唯一允许的版本。但是当点击连接到stop_client()
的按钮时,这会使GUI冻结我真的建议转到QThreads与PyQt5一起使用。他们还有一个额外的优势,就是能够被杀死。以及能够更好地使用PyQts信号和插槽系统
但是,对于使用常规线程模块,您可以将其子类化并添加一个切换标志,该标志在线程运行时进行检查,并在更改时使其停止。一个非常基本的事件循环
import time
import threading
class MyThread(threading.Thread):
def __init__(self, *args, **kwargs):
super(MyThread, self).__init__(*args, **kwargs)
self.terminate = False
def run(self): # This needs to the function name! Do your thing in this
while not self.terminate:
print('Do Stuff, state is ', self.terminate)
time.sleep(1) # As long as the "Do stuff" happens fast, it checks every one second
if __name__ == '__main__':
t = MyThread()
t.start() # Note, we use .start() but define what it does in the .run method.
time.sleep(5)
t.terminate = True
使用此代码,理想情况下,在将terminate设置为True后,代码最多停止一秒钟。如果client_run()停止代码执行,那么您可能会遇到问题。
如果在运行期间需要,还可以将用户名、密码存储在类init中