[英]Python threading module - GUI still freezing
我用GUI構建了一個Twitter搜尋器,該GUI可以從任何給定的Twitter帳戶中獲取最新的20條推文,並將它們保存到csv文件中。
搜尋器應每x分鍾( timeIntervall )重復搜尋 y次( times )。 當搜尋器當前繁忙時,GUI會凍結,因此我嘗試通過線程解決此問題:
app = QtWidgets.QApplication(sys.argv)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Twitter Crawler")
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.onPushButtonClick)
def onPushButtonClick(self):
def working(self):
url = self.ui.urlInput.text()
timeIntervall = self.ui.timeIntervall.text()
seconds = timeIntervall.split(":")
seconds = int(seconds[0]) * 60 * 60 + int(seconds[1]) * 60
times = self.ui.crawlcount.value()
fetcher = ArticleFetcher(url)
print(times)
firstFetch = True
for count in range(0, times):
if firstFetch:
fetcher.fetch()
firstFetch = False
else:
time.sleep(seconds)
fetcher.fetch()
worker = threading.Thread(target=working, args=(self,))
worker.start()
worker.join()
window = MainWindow()
window.show()
sys.exit(app.exec())
輸入timeIntervall , times和pushButton之后 ,將啟動一個工作線程來處理爬網。 該應用程序正在運行,但是GUI仍然凍結。
我懷疑我需要另一個線程來處理GUI,並嘗試了以下操作:
def gui():
window = MainWindow()
window.show()
sys.exit(app.exec())
rungui = threading.Thread(target=gui)
rungui.start()
rungui.join()
現在,GUI僅非常短暫地打開,然后立即再次關閉。
有什么建議如何解決這個問題? 還是不使用PyQt線程模塊可能很愚蠢?
線程的join()方法等待線程完成。 啟動工作線程時,讓它自己運行。 如果需要顯示進度,請使用Queue並將消息從工作線程發送到主線程(在某些計時器循環中使用get_nowait()來查看工作線程是否發送了重要的消息)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.