簡體   English   中英

如何在 PyQt5 中停止線程

[英]How to Stop a thread in PyQt5

我嘗試尋找我的問題的解決方案,但我似乎無法找到正確的方法,在 GUI 沒有“無響應”的情況下停止它

基本上繼承人如何啟動和停止它:

    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 中存儲用戶名、密碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM