Python - 关闭tkinter GUI窗口时线程出错

时间:2018-02-21 23:47:29

标签: python tkinter

我正在运行一个函数,在我的tkinter运行时更改线程中的标签值。除非我在线程停止之前关闭窗口,否则此代码有效。我已附上以下错误。

如何解决此问题?使用tkinter时是否有更好的方法来设置这些线程?

代码(除非我提前关闭GUI窗口,否则有效):

from tkinter import *
from tkinter import ttk
import threading
import time

def fun():
    for i in range(10):
        var.set(var.get() + 1)
        print(var.get())
        time.sleep(.5)

t = threading.Thread(target=fun)

root = Tk()

var = IntVar()
var.set(0)

mainframe = ttk.Frame(root)
mainframe.grid(column = 0, row = 0)
label = ttk.Label(mainframe, textvariable=var)
label.grid(column = 0, row = 0)

t.start()
root.mainloop()
t.join()
print('Done')

fun()完成运行之前关闭GUI窗口时出错:

Exception in thread Thread-1:
Done
Traceback (most recent call last):
  File "C:\Users\PC-User\AppData\Local\Programs\Python\Python36-32\Lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Users\PC-User\AppData\Local\Programs\Python\Python36-32\Lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "C:/Users/PC-User/PycharmProjects/Arb/example.py", line 8, in fun
    var.set(var.get() + 1)
  File "C:\Users\PC-User\AppData\Local\Programs\Python\Python36-32\Lib\tkinter\__init__.py", line 503, in get
    value = self._tk.globalgetvar(self._name)
RuntimeError: main thread is not in main loop

0 个答案:

没有答案