<p><a href="https://stackoverflow.com/a/538559/355230">solution posted by Bjorn</a>在我的计算机上导致“RuntimeError:Calling Tcl from different appartment”消息(RedHat Enterprise 5,python 2.6.1)。Bjorn可能没有收到此消息,因为根据<a href="http://www.mail-archive.com/tkinter-discuss@python.org/msg01808.html" rel="noreferrer">one place I checked</a>,使用Tkinter错误处理线程是不可预测的,并且依赖于平台。</p>
<p>问题似乎是<code>app.start()</code>算作对Tk的引用,因为app包含Tk元素。我通过在<code>__init__</code>内部用<code>self.start()</code>替换<code>app.start()</code>来解决这个问题。我还使所有的Tk引用要么在调用<code>mainloop()</code></em>的<em>函数中,要么在调用<code>mainloop()</code>的函数调用的<em>函数中(这显然对于避免“不同单元”错误非常重要)。</p>
<p>最后,我添加了一个带有回调的协议处理程序,因为如果没有回调,当用户关闭Tk窗口时,程序将以错误退出。</p>
<p>修订后的准则如下:</p>
<pre><code># Run tkinter code in another thread
import tkinter as tk
import threading
class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def callback(self):
self.root.quit()
def run(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
label = tk.Label(self.root, text="Hello World")
label.pack()
self.root.mainloop()
app = App()
print('Now we can continue running code while mainloop runs!')
for i in range(100000):
print(i)
</code></pre>