簡體   English   中英

如何停止在 python 中運行的線程

[英]How to stop a thread running in python

我正在開發一個帶有 Python 的應用程序。我想要做的是當我按下按鈕 1 時線程工作,當我按下按鈕 2 時線程停止。我該怎么做。

這是我的代碼:

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()

可能最簡單的方法是在全局變量 scope 中創建一個變量來指示線程是否應該運行;

runthread = True

線程應該定期檢查這是否仍然是True 如果沒有,它應該簡單地返回:

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

鏈接到 stopButton 的stopButton現在所要做的就是將runthread設置為False

def do_stop():
    global runthread
    runthread = False

順便說一句,您不必 go 並為main創建一個單獨的線程。

這是一個運行單獨線程的 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