i get this error “RuntimeError: threads can only be started once” when i click close and then click run again

对着背影说爱祢 提交于 2021-02-11 12:40:52

问题


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....i'm using threading to somehow make my ui works when it it's into loop, when i close the loop and i can't restart it again.


回答1:


As the error said, terminated thread cannot be started again.

You need to create another thread:

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


来源:https://stackoverflow.com/questions/63450516/i-get-this-error-runtimeerror-threads-can-only-be-started-once-when-i-click-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!