【问题标题】:concurrent.futures, selenium and tkinter freeze problemconcurrent.futures、selenium 和 tkinter 冻结问题
【发布时间】:2020-03-28 08:51:10
【问题描述】:

我有一个问题,我无法理解这些库。

我的主要代码如下所示:

import tkinter as tk
import concurrent.futures
from news_bar import NewsBar        
from fbscout import FbScout         #it bases on sellenium

def run():
    scout.login(USER_EMAIL, USER_PASS)

    while True:
        news = str(scout.check_news())
        if news:
            news_bar.add_text(news)

if __name__ == "__main__":
root = tk.Tk()
news_bar = NewsBar(root)
scout = FbScout.Scrpper()
scout.set_groups(GROUPS)

with concurrent.futures.ThreadPoolExecutor() as executor:
    gui = executor.submit(news_bar.mainloop())
    sc = executor.submit(scout.run_browser())
    run = executor.submit(run())

运行 tkinter 的 gui 主循环后,程序冻结并且不执行其余代码。

gui = executor.submit(news_bar.mainloop())

我不知道如何命令程序不要等到无限循环执行......当我关闭 tkinter 的窗口时,它会走得更远

评论: 总结一下。我有两个函数 news_bar.mainloop() 等待事件和 run() 是无限循环。而且我希望它们同时工作并且彼此独立。

【问题讨论】:

  • While True:,怎么破解?
  • 我没有。程序正在创建过程中。我添加了这些行以查看是否一切正常。但它仍然没有......甚至在我不关闭 tkinter 的 gui 窗口之前都没有达到这些线。
  • 你需要使用另一个线程来使用for循环来运行你的add_text
  • 即使我这样做了,线程仍然被gui线程阻塞......

标签: python-3.x multithreading selenium tkinter threadpoolexecutor


【解决方案1】:

在您关闭窗口之前,mainloop 函数不会完成(假设您没有传递参数)。

也许另一个线程会解决您的问题?

【讨论】:

  • 好吧,我已经添加了负责检查无限循环中更新的线程。但是主循环仍然需要一个事件并且不允许继续剩余的线程。
【解决方案2】:

有效!需要创建一个继承第一个主 tkinter 类的新类,并在其中放置 selenium 基础模块。

class FbBar(NewsBar):
def __init__(self, master):
    NewsBar.__init__(self, master)
    scout = FbScout.Scrpper()
    scout.set_groups(GROUPS)
    self.update()
    t = threading.Thread(target=self.prepare_browser, args=[scout])
    t.start()

@staticmethod
def prepare_browser(scout):
    scout.run_browser()
    scout.login(USER_EMAIL, USER_PASS)



root = tk.Tk()
news_bar = FbBar(root)
news_bar.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    相关资源
    最近更新 更多