【问题标题】:i get this error "RuntimeError: threads can only be started once" when i click close and then click run again当我单击关闭然后再次单击运行时,我收到此错误“RuntimeError:线程只能启动一次”
【发布时间】:2020-08-17 20:35:42
【问题描述】:
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 在它进入循环时工作,当我关闭循环并且我无法再次重新启动它时。

【问题讨论】:

  • 正如错误所说,终止的线程无法再次启动。您需要创建另一个线程。
  • 我该怎么做?

标签: python-3.x tkinter python-multithreading


【解决方案1】:

正如错误所说,终止的线程无法再次启动。

你需要创建另一个线程:

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

【讨论】:

  • daemon 设置为 True 的线程将在主应用程序退出时终止。见here
猜你喜欢
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-17
  • 1970-01-01
  • 1970-01-01
  • 2021-08-24
  • 1970-01-01
相关资源
最近更新 更多