赞
踩
I am making a GUI using Tkinter with two main buttons: "Start" and "Stop". Could you, please, advise on how to make the "Stop" button to terminate the already running function called by "Start" button for the following code?
The problem as you may expect is that the entire window including the "Stop" button is stuck/not responsive while "start" function is running.
The "start" function extracts some information from a number of html files which may take pretty while (for 20 huge files it can take around 10 minutes), and I would like for a user to be able to interrupt that process at any moment.
from tkinter import *
import Ostap_process_twitter_file_folder
root = Tk()
def start (event):
Ostap_process_twitter_file_folder.start_extraction()
def stop (event):
# stop "start" function
label1 = Label(root, text = "source folder").grid(row=0)
label2 = Label(root, text = "output folder").grid(row=1)
e_sF = Entry(root)
e_oF = Entry(root)
e_sF.grid(row=0, column=1)
e_oF.grid(row=1, column=1)
startButton = Button(root, text = "start")
startButton.grid(row=2)
startButton.bind("", start)
stopButton = Button(root, text = "stop")
stopButton.grid(row=2, column=1)
stopButton.bind("", stop)
root.mainloop()
I suppose that using threads will be a solution for this issue. Although I've been looking through similar questions here on stackoverflow and various introductory resources on threading in Python (not that much introductory, btw), it is still not clear for me how exactly to implement those suggestions to this particular case.
解决方案
why do you think using threads would be a solution? ...
you cannot stop a thread/process even from the main process that created/called it. (at least not in a mutliplatform way ... if its just linux thats a different story)
instead you need to modify your Ostap_process_twitter_file_folder.start_extraction() to be something more like
halt_flag = False
def start_extraction(self):
while not Ostap_process_twitter_file_folder.halt_flag:
process_next_file()
then to cancel you just do Ostap_process_twitter_file_folder.halt_flag=True
oh since you clarified i think you just want to run it threaded ... I assumed it was already threaded ...
def start(evt):
th = threading.Thread(target=Ostap_process_twitter_file_folder.start_extraction)
th.start()
return th
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。