简体   繁体   English

使用 tkinter 按钮停止多个线程

[英]Using tkinter button to stop multiple threads

I'm trying to use a button to stop all threads I've created in the for loop.我正在尝试使用一个按钮来停止我在 for 循环中创建的所有线程。 Is there a method to stop threads?有没有办法停止线程?

Here's my code:这是我的代码:

import threading
import time
from tkinter import *

tk= Tk()

class go(threading.Thread):

    def __init__(self,c):
        threading.Thread.__init__(self)
        self.c = c
    def run(self):
        while 1 == 1 :
            time.sleep(5)
            print('This is thread: '+str(self.c))


for count in range(10):
    thread = go(count)
    thread.start()

btn1 = Button(tk, text="Stop All", width=16, height=5)
btn1.grid(row=2,column=0)

tk.mainloop()

You need to provide a condition to quit the while loop in the run() method.您需要在run()方法中提供退出 while 循环的条件。 Normally threading.Event object is used:通常使用threading.Event对象:

def __init__(self, c):
    ...
    self.stopped = threading.Event()

Then you need to check whether the Event object is set using Event.is_set() :然后您需要检查是否使用Event.is_set()设置了Event对象:

def run(self):
    while not self.stopped.is_set():
        ...

So to terminate the thread, just set the Event object.所以要终止线程,只需设置Event对象。 You can create a class method to do it:您可以创建一个类方法来做到这一点:

def terminate(self):
    self.stopped.set()

Below is a modified example based on yours:以下是基于您的修改示例:

import threading
import time
from tkinter import *

tk = Tk()

class go(threading.Thread):
    def __init__(self,c):
        threading.Thread.__init__(self)
        self.c = c
        self.stopped = threading.Event()

    def run(self):
        while not self.stopped.is_set():
            time.sleep(5)
            print(f'This is thread: {self.c}')
        print(f'thread {self.c} done')

    def terminate(self):
        self.stopped.set()


threads = []  # save the created threads
for count in range(10):
    thread = go(count)
    thread.start()
    threads.append(thread)

def stop_all():
    for thread in threads:
        thread.terminate()

btn1 = Button(tk, text="Stop All", width=16, height=5, command=stop_all)
btn1.grid(row=2, column=0)

tk.mainloop()

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

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