【发布时间】:2018-03-30 23:57:55
【问题描述】:
我正在创建一个运行多个线程的程序,其中每个线程更新一个变量,然后使用tkinter 显示该值。
唯一的问题是,每当我尝试更新显示时,我都会收到 RuntimeError:
Exception in thread Thread-x:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "program.py", line 15, in body
update()
File "program.py", line 11, in update
display.config({"text" : "x = {0}".format(x)})
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1479, in configure
return self._configure('configure', cnf, kw)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1470, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
RuntimeError: main thread is not in main loop
我尝试修复错误的一些解决方案是:
- 使显示对象成为函数的全局对象(使用
global) - 创建一个单独的函数来更新显示
但是,这些解决方案都不起作用(RuntimeError 仍然不断出现)。
下面是我的程序:
import tkinter, time, threading
window = tkinter.Tk()
x = 0
display = tkinter.Label(window)
display.pack()
def update():
global x
x += 1
display.config({"text" : "x = {0}".format(x)}) #It says the error is on this line
def body():
time.sleep(3)
update()
body()
def start_threads():
for i in range(5):
thread = threading.Thread(target=body)
thread.start(); thread.join()
start = tkinter.Button(window, text="Start", command=start_threads)
start.pack()
我不知道如何修复 RuntimeError,因此我们将不胜感激。
【问题讨论】:
标签: python multithreading python-3.x tkinter runtime-error