线程在Tkinter

时间:2015-05-22 16:29:12

标签: python multithreading tkinter

我在Tkinter中遇到线程问题。我读到除了主GUI线程之外,事情应该在不同的线程中完成。每当我点击按钮,它就会在线程停止后关闭。我认为我没有正确实现线程。

from Tkinter import *
from scrapy import cmdline
import thread

def scrapeMe():
    if(RadioVar.get() == 1):
        thread.start_new_thread(cmdline.execute("scrapy crawl s1".split()))
    if(RadioVar.get() == 2):
        thread.start_new_thread(cmdline.execute("scrapy crawl s2".split()))


root = Tk()

B1 = Button(root, text="Scrape", command = scrapeMe)

RadioVar = IntVar()

R1 = Radiobutton(root, text = "1", variable = RadioVar, value=1)
R2 = Radiobutton(root, text = "2", variable = RadioVar, value=2)


B1.pack()
R1.pack()
R2.pack()
root.mainloop()

1 个答案:

答案 0 :(得分:0)

我解决了大部分问题。第一个是,您以错误的方式使用了“线程”。我不确定如何使用scrapy,所以我会把它留给你或其他人。至少,我让它为你运行。

from tkinter import *
from scrapy import cmdline
import threading

def scrapeMe():
    if(RadioVar.get() == 1):
        threading.Thread(cmdline.execute("scrapy crawl s1".split()))
    if(RadioVar.get() == 2):
        threading.Thread(cmdline.execute("scrapy crawl s2".split()))


root = Tk()

B1 = Button(root, text="Scrape", command = scrapeMe)

RadioVar = IntVar()

R1 = Radiobutton(root, text = "1", variable = RadioVar, value=1)
R2 = Radiobutton(root, text = "2", variable = RadioVar, value=2)


B1.pack()
R1.pack()
R2.pack()
root.mainloop()