tkinter error on python 3 (RuntimeError: Calling Tcl from different appartment)

tkinter error on python 3 (RuntimeError: Calling Tcl from different appartment)

以下代码不适用于 python3.5(运行时错误:从不同的公寓调用 Tcl) 但它在 python 2.7 上运行良好 很难知道问题的原因以及如何解决它。

import tkinter
import threading

class MyTkApp(threading.Thread):
    def __init__(self):
        self.root=tkinter.Tk()
        self.s = tkinter.StringVar()
        self.s.set('Foo')
        l = tkinter.Label(self.root,textvariable=self.s)
        l.pack()
        threading.Thread.__init__(self)

    def run(self):
        self.root.mainloop()


app = MyTkApp()
app.start()

必须只能从单个线程访问 tkinter,特别是主线程(除非您真的非常勇敢)。当所有其他线程希望 GUI 更新发生时,它们需要向主线程发送消息;有很多线程间发送消息的机制。

线程规则是这样的,因为底层库广泛使用特定于线程的数据(以避免需要像全局解释器锁这样的东西)。您真的不能从另一个线程更新 GUI;当你尝试这样做时,系统肯定会爆炸。