我收到此错误&运行错误:当我单击关闭,然后再次单击运行时,线程只能启动一次 [英] i get this error "RuntimeError: threads can only be started once" when i click close and then click run again

查看:16
本文介绍了我收到此错误&运行错误:当我单击关闭,然后再次单击运行时,线程只能启动一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于我收到此错误&运行错误:当我单击关闭,然后再次单击运行时,线程只能启动一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆