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

戏子无情 提交于 2020-01-05 08:53:14

问题


The below code doesn't work on python3.5 (RuntimeError: Calling Tcl from different appartment) But It works well on python 2.7 It is hard to know the reason of problem and how can i fix it.

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

回答1:


You must only access tkinter from a single thread, specifically the main thread (unless you are really very brave indeed). All other threads need to send messages to the main thread when they want GUI updates to happen; there's lots of mechanisms for sending messages between threads.

The threading rule is that way because of the underlying library's extensive use of thread-specific data (in order to avoid needing something like a global interpreter lock). You really can't update the GUI from another thread; the system will definitely blow up when you try to do so.



来源:https://stackoverflow.com/questions/47008443/tkinter-error-on-python-3-runtimeerror-calling-tcl-from-different-appartment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!