繁体   English   中英

Python线程模块-GUI仍然冻结

[英]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())

输入timeIntervalltimespushButton之后 ,将启动一个工作线程来处理爬网。 该应用程序正在运行,但是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM