Python Verison 3.7 | NPM版本6.2.0 | Google Lighthouse Package版本4.0.0
我试图创建一个相当简单的Tkinter窗口来自动执行Google灯塔NPM程序包,但是在尝试停止线程时却失败了。
线程:
lighthouse_thread = threading.Thread(target=start_lighthouse)
和启动线程的按钮:
Start_Ligthouse = Button(root, text="Starten", command=lighthouse_thread.start)
Start_Ligthouse.place(x=850, y=312)
Start_Ligthouse.config(state=DISABLED)
root.after(100, CheckInOut)
函数如下:
def start_lighthouse():
global filenumber
global reportlocation
global instantkill
global file
Start_Ligthouse.config(state=DISABLED)
for url in file:
url = url.rstrip("\n")
print(url)
filename = url.replace("https","").replace("/","-").replace("\n","").replace(":","").replace("--","")
if os.path.isfile(reportlocation + "/" + filename + ".html"):
print("EXISTS!")
filenumber = 2
while True:
newfilename = filename + "{}".format(filenumber)
if not os.path.isfile(reportlocation + "/" + newfilename + ".html"):
filename = newfilename
break
filenumber += 1
if instantkill:
break
#os.system("lighthouse --disable-device-emulation --throttling-method=provided --preset=perf --quiet --output-path={}/{}.html {}".format(reportlocation,filename,url))
CheckIn = False
CheckOut = False
print("LoopEnded")
我评论了os.system命令,以便可以快速浏览列表。如果我再次调用该函数,则会收到一个错误,指出该线程无法启动两次(据我了解)。但是据我了解,该线程应在函数完成后终止。
我的问题是:如何使线程在完成应做的工作后终止?
答案 0 :(得分:0)
感谢@JamesKent我修复了它。
我创建了一个创建线程的函数,而不是使用按钮调用线程。
def create_thread():
print("Thread Created")
lighthouse_thread = threading.Thread(target=start_lighthouse)
lighthouse_thread.start()
按钮现在调用此函数,从而创建一个新线程。
Start_Ligthouse = Button(root, text="Starten", command=create_thread)