使用 tkinter 按钮停止多个线程
Using tkinter button to stop multiple threads
我正在尝试使用一个按钮来停止我在 for 循环中创建的所有线程。有没有停止线程的方法?
这是我的代码:
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()
您需要在 run()
方法中提供退出 while 循环的条件。通常使用 threading.Event
对象:
def __init__(self, c):
...
self.stopped = threading.Event()
然后你需要检查 Event
对象是否使用 Event.is_set()
:
设置
def run(self):
while not self.stopped.is_set():
...
所以要终止线程,只需设置Event
对象。您可以创建一个 class 方法来执行此操作:
def terminate(self):
self.stopped.set()
下面是基于您的修改示例:
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()
我正在尝试使用一个按钮来停止我在 for 循环中创建的所有线程。有没有停止线程的方法?
这是我的代码:
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()
您需要在 run()
方法中提供退出 while 循环的条件。通常使用 threading.Event
对象:
def __init__(self, c):
...
self.stopped = threading.Event()
然后你需要检查 Event
对象是否使用 Event.is_set()
:
def run(self):
while not self.stopped.is_set():
...
所以要终止线程,只需设置Event
对象。您可以创建一个 class 方法来执行此操作:
def terminate(self):
self.stopped.set()
下面是基于您的修改示例:
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()