如何解决单击关闭,然后再次单击运行时,出现此错误“ RuntimeError:线程只能启动一次”
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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。