问题描述
import threading
from tkinter import *
running = False
def run():
global running
c = 1
running = True
while running:
print(c)
c += 1
run_thread = threading.Thread(target=run)
def kill():
global running
running = False
root = Tk()
button = Button(root,text='Run',command=run_thread.start)
button.pack()
button1 = Button(root,text='close',command=kill)
button1.pack()
button2 = Button(root,text='Terminate',command=root.destroy)
button2.pack()
root.mainloop()
click here for error img ....我正在使用线程以某种方式使我的ui在进入循环时,在关闭循环且无法再次重新启动时起作用。
解决方法
如错误所述,终止的线程无法再次启动。
您需要创建另一个线程:
import threading
from tkinter import *
running = False
def run():
global running
c = 1
running = True
while running:
print(c)
c += 1
def start():
if not running:
# no thread is running,create new thread and start it
threading.Thread(target=run,daemon=True).start()
def kill():
global running
running = False
root = Tk()
button = Button(root,text='Run',command=start)
button.pack()
button1 = Button(root,text='close',command=kill)
button1.pack()
button2 = Button(root,text='Terminate',command=root.destroy)
button2.pack()
root.mainloop()