问题
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