scrapy 和 tkinter 怎么配合使用?

how to use scrapy with tkinter smoothly?

我想将 scrapy 与我用 tkinter 制作的 GUI 一起使用,而 spider 单独和 GUI 都可以正常工作,但是当我使用 GUI 按钮启动 scrapy spider 时,GUI 没有响应,如您在中看到的图片。

enter image description here

这是我的代码:

from tkinter import *
import subprocess

class Test():
    def __init__(self):
        self.root = Tk()
        self.root.geometry('300x200')
        self.button = Button(self.root,
                          text = 'Click Me',
                          command=lambda:self.pop_up())
        self.button.pack()
    self.root.mainloop()


def scrape(self):
   process = subprocess.Popen("scrapy runspider url_scraper.py -o output.csv")
   process.wait()

def pop_up(self):
    top = Toplevel()

    btn = Button(top, text="Output filename: ")
    e = Entry(top)
    scrape = Button(top, text="Start", command=lambda: [top.destroy(), self.scrape()])

    btn.grid(row=0, column=0)
    e.grid(row=1, column=1)
    scrape.grid(row=2, column=0)


app = Test()

我只是想让它们在我的抓取工具抓取数据时不要挂起。请帮我解决这个问题。

提前致谢。

process.wait() 等待进程完成,阻止 GUI 的主循环 运行。您可以删除它,或使用 threading.

from threading import Thread

def threaded_function(arg):
    process = subprocess.Popen("scrapy runspider url_scraper.py -o output.csv")

thread = Thread(target = threaded_function, args = (an_argument, ))
thread.start()