【问题标题】:How to make "Stop" button to terminate "start" function already running in Tkinter (Python)如何使“停止”按钮终止已经在 Tkinter(Python)中运行的“开始”功能
【发布时间】:2015-12-18 12:04:18
【问题描述】:

我正在使用带有两个主要按钮的 Tkinter 制作 GUI:“开始”和“停止”。您能否建议如何使“停止”按钮终止以下代码的“开始”按钮调用的已经运行的函数?

您可能预料到的问题是,在“开始”功能运行时,包括“停止”按钮在内的整个窗口都卡住/没有响应。

“开始”功能从许多 html 文件中提取一些信息,这可能需要相当长的时间(对于 20 个大文件可能需要大约 10 分钟),我希望用户能够在任何时候。

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("<Button-1>", start)

    stopButton = Button(root, text = "stop")
    stopButton.grid(row=2, column=1)
    stopButton.bind("<Button-1>", stop)

    root.mainloop()

我认为使用线程将是解决此问题的方法。尽管我一直在查看有关 stackoverflow 的类似问题以及有关 Python 线程的各种介绍性资源(不是那么多介绍性的,顺便说一句),但我仍然不清楚如何针对这种特殊情况实施这些建议。

【问题讨论】:

    标签: python multithreading user-interface tkinter


    【解决方案1】:

    您为什么认为使用线程是一种解决方案? ...

    即使是创建/调用它的主进程,您也无法停止线程/进程。 (至少不是以多平台的方式......如果它只是 linux 那就不同了)

    相反,您需要将 Ostap_process_twitter_file_folder.start_extraction() 修改为更像

    halt_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

    哦,既然你澄清了,我想你只是想用线程运行它......我以为它已经是线程的......

    def 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 被解锁,我希望能够按下停止按钮,这将停止 start_extraction 功能。后一个功能将如何停止还不是我的问题
    • 谢谢,太好了!我提供了有关我的问题的更多信息,并且我对线程的猜测是正确的。我现在可以让@joran 投票而不是投票吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2014-01-21
    • 1970-01-01
    • 2020-04-28
    • 2019-05-12
    • 1970-01-01
    • 2017-01-26
    相关资源
    最近更新 更多