python线程暂停_关于多线程:如何使“停止”按钮终止已经在Tkinter中运行的“开始”功能(Python)...
我正在使用帶有兩個主要按鈕的Tkinter制作GUI:"開始"和"停止"。 您能否為以下代碼提供建議,以使"停止"按鈕終止由"開始"按鈕調用的已運行功能?
您可能會想到的問題是,在運行"啟動"功能時,包括"停止"按鈕在內的整個窗口都被卡住/沒有響應。
"開始"功能從許多html文件中提取一些信息,這可能會花費一些時間(對于20個大文件來說,可能需要10分鐘左右的時間),我希望用戶能夠隨時中斷該過程。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28from 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()
我想使用線程將是解決此問題的方法。 盡管在這里我一直在研究類似的有關stackoverflow的問題以及有關Python線程的各種入門資源(沒有那么多的入門知識,順便說一句),但對于我來說仍然不清楚如何針對這些特殊情況準確實現這些建議。
您為什么認為使用線程是一種解決方案? ...
您甚至不能從創建/調用線程的主進程中停止線程/進程。 (至少不是以mutliplatform的方式...如果只是linux多數民眾贊成在另外一個故事)
相反,您需要將Ostap_process_twitter_file_folder.start_extraction()修改為更像
1
2
3
4halt_flag = False
def start_extraction(self):
while not Ostap_process_twitter_file_folder.halt_flag:
process_next_file()
然后取消即可,只需執行Ostap_process_twitter_file_folder.halt_flag=True
哦,既然您澄清了,我想您只是想以線程方式運行它...我以為它已經是線程...
1
2
3
4def start(evt):
th = threading.Thread(target=Ostap_process_twitter_file_folder.start_extraction)
th.start()
return th
謝謝@Joran。 我說的是一個不同的問題。 當start_extraction函數運行時,整個GUI都會被阻塞,即使當我使用您的halt_flag解決方案時,它也不會更改任何內容,因為由于GUI卡住,我仍然無法從GUI進行任何操作。 我想要的是在" start_extraction"運行時使GUI暢通無阻。 并且一旦GUI被解除阻止,我希望能夠按下Stop按鈕,這將停止start_extraction功能。 我的問題尚不明確如何停止后者的功能
謝謝,太好了! 我提供了有關我的問題的更多信息,我對線程的猜測是正確的。 我可以投票代替@joran投票嗎?
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的python线程暂停_关于多线程:如何使“停止”按钮终止已经在Tkinter中运行的“开始”功能(Python)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python数据分析是什么意思_pyth
- 下一篇: websocket python爬虫_p