简体   繁体   English

如何停止在 python 中运行的线程

[英]How to stop a thread running in python

I am developing an application with Python. What I want to do is that the Thread works when I press Button 1, the Thread stops when I press Button 2. How can I do this.我正在开发一个带有 Python 的应用程序。我想要做的是当我按下按钮 1 时线程工作,当我按下按钮 2 时线程停止。我该怎么做。

Here is my code:这是我的代码:

from tkinter import *
import threading

def process():
    while True:
        print("Hello World")
processThread = threading.Thread(target=process)


def main():
    mainWindow = Tk()
    mainWindow.resizable(FALSE, FALSE)

    mainWindow.title("Text")
    mainWindow.geometry("500x250")

    recButton=Button(mainWindow)
    recButton.config(text="Button 1", font=("Arial", "13"), bg="red",fg="white", width="15", command=)
    recButton.place(x=15,y=10)

    stopButton=Button(mainWindow)
    stopButton.config(text="Button 2", font=("Calibri", "13"), bg="orange",fg="white", width="15", command=)
    stopButton.place(x=15,y=55)

    textBox = Text(mainWindow, height="14", width="37")
    textBox.place(x=180, y=10)

    mainWindow.mainloop()
mainThread = threading.Thread(target=main)
mainThread.start()

Probably the easiest way is to create a variable in the global scope that indicates if the thread should run;可能最简单的方法是在全局变量 scope 中创建一个变量来指示线程是否应该运行;

runthread = True

The thread should regularly check if this is still True .线程应该定期检查这是否仍然是True If not, it should simply return:如果没有,它应该简单地返回:

def process():
    while runthread:
        print("Hello World")

All that the function linked to the stopButton now has to do is to set runthread to False .链接到 stopButton 的stopButton现在所要做的就是将runthread设置为False

def do_stop():
    global runthread
    runthread = False

BTW, you don't have to go and create a separate thread for main .顺便说一句,您不必 go 并为main创建一个单独的线程。

Here is an example of a tkinter program running a separate thread;这是一个运行单独线程的 tkinter 程序示例;

"""Example tkinter script showing the use of a thread."""

import os
import sys
import threading
import time
import tkinter as tk
import tkinter.font as tkfont
import types

__version__ = "2022.02.02"
# Namespace for widgets that need to be accessed by callbacks.
widgets = types.SimpleNamespace()
# State that needs to be accessed by callbacks.
state = types.SimpleNamespace()


def create_widgets(root, w):
    """
    Create the window and its widgets.

    Arguments:
        root: the root window.
        w: SimpleNamespace to store widgets.
    """
    # General commands and bindings
    root.wm_title("tkinter threading v" + __version__)
    root.columnconfigure(2, weight=1)
    root.rowconfigure(3, weight=1)
    root.resizable(False, False)
    # First row
    tk.Label(root, text="Thread status: ").grid(row=0, column=0, sticky="ew")
    w.runstatus = tk.Label(root, text="not running", width=12)
    w.runstatus.grid(row=0, column=1, sticky="ew")
    # Second row
    tk.Label(root, text="Timer: ").grid(row=1, column=0, sticky="ew")
    w.counter = tk.Label(root, text="0 s")
    w.counter.grid(row=1, column=1, sticky="ew")
    # Third row
    w.gobtn = tk.Button(root, text="Go", command=do_start)
    w.gobtn.grid(row=2, column=0, sticky="ew")
    w.stopbtn = tk.Button(root, text="Stop", command=do_stop, state=tk.DISABLED)
    w.stopbtn.grid(row=2, column=1, sticky="ew")


def initialize_state(s):
    """
    Initialize the global state.

    Arguments:
        s: SimpleNamespace to store application state.
    """
    s.worker = None
    s.run = False
    s.counter = 0


def worker():
    """
    Function that is run in a separate thread.

    This function *does* update tkinter widgets.  In Python 3, this should be
    safe if a tkinter is used that is built with threads.
    """
    # Initialization
    widgets.runstatus["text"] = "running"
    # Work
    while state.run:
        time.sleep(0.25)
        state.counter += 0.25
        widgets.counter["text"] = f"{state.counter:.2f} s"
    # Finalization
    state.counter = 0.0
    widgets.counter["text"] = f"{state.counter:g} s"
    widgets.runstatus["text"] = "not running"


def do_start():
    """Callback for the “Go” button"""
    widgets.gobtn["state"] = tk.DISABLED
    widgets.stopbtn["state"] = tk.NORMAL
    state.run = True
    state.worker = threading.Thread(target=worker)
    state.worker.start()


def do_stop():
    """Callback for the “Stop” button"""
    widgets.gobtn["state"] = tk.NORMAL
    widgets.stopbtn["state"] = tk.DISABLED
    state.run = False
    state.worker = None


# Main program starts here.
if __name__ == "__main__":
    # Detach from the command line on UNIX systems.
    if os.name == "posix":
        if os.fork():
            sys.exit()
    # Initialize global state
    initialize_state(state)
    # Create the GUI window.
    root = tk.Tk(None)
    # Set the font
    default_font = tkfont.nametofont("TkDefaultFont")
    default_font.configure(size=12)
    root.option_add("*Font", default_font)
    create_widgets(root, widgets)
    root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM