简体   繁体   English

Python线程模块-GUI仍然冻结

[英]Python threading module - GUI still freezing

I built a twitter crawler with GUI that fetches the latest 20 tweets from any given Twitter Account and saves them into a csv file. 我用GUI构建了一个Twitter搜寻器,该GUI可以从任何给定的Twitter帐户中获取最新的20条推文,并将它们保存到csv文件中。

The crawler should repeat crawling every x minutes ( timeIntervall ) for y times ( times ). 搜寻器应每x分钟( timeIntervall )重复搜寻 y次( times )。 The GUI freezes when the crawler is currently busy, so I tried to solve this with threading: 当搜寻器当前繁忙时,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())

After entering timeIntervall , times and pushButton is clicked, a worker thread is started which handles the crawling. 输入timeIntervalltimespushButton之后 ,将启动一个工作线程来处理爬网。 The application is running, but GUI is still freezing. 该应用程序正在运行,但是GUI仍然冻结。

I suspected that I would need another thread for the GUI and tried the following: 我怀疑我需要另一个线程来处理GUI,并尝试了以下操作:

def gui():
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

rungui = threading.Thread(target=gui)
rungui.start()
rungui.join()

Now the GUI opens only very briefly and then closes again immediately. 现在,GUI仅非常短暂地打开,然后立即再次关闭。

Any suggestions how to solve this? 有什么建议如何解决这个问题? Or is it maybe silly not to use the PyQt threading module? 还是不使用PyQt线程模块可能很愚蠢?

The Thread's join() method waits for thread to complete. 线程的join()方法等待线程完成。 When you start your worker thread, let it run by itself. 启动工作线程时,让它自己运行。 If you need to display it's progress, use Queue and send messages from worker thread to main thread (use get_nowait() in some timer loop to see if the worker thread has sent something important). 如果需要显示进度,请使用Queue并将消息从工作线程发送到主线程(在某些计时器循环中使用get_nowait()来查看工作线程是否发送了重要的消息)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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