当前位置:   article > 正文

pythontkinter使按钮失效,如何使“停止"按钮终止“开始"按钮.函数已在Tkinter中运行(Python)...

tkinter button失效

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/124990
推荐阅读
相关标签
  

闽ICP备14008679号