2014-04-16 110 views
1

我对tkinter Toplevel小部件有点问题。每当我尝试销毁顶层窗口时,它都不会关闭,而是会变为非活动状态。每当我点击应该被销毁的窗口时,我都会遇到内存地址错误。有人知道我在做什么错吗?python tkinter销毁顶层

示例代码:

from tkinter import * 
import _thread as thread 
import time 
root = Tk() 
root.title('root') 
login = Toplevel(root) 
login.title('login') 
thread.start_new_thread(root.mainloop,()) 
time.sleep(3) 
login.destroy() 
+0

不要使用'time.sleep()'在异步代码。 –

+0

即使没有'destroy'行,我也会得到'RuntimeError:从不同公寓调用Tcl'。似乎Tkinter对线程一般不会很好。 – Kevin

+0

@凯文:你是对的。 –

回答

1

Tkinter的不是线程安全的。所有的Tkinter调用应该来自单个线程。使用root.after可以安排延迟后发生的函数调用。

from tkinter import * 
root = Tk() 
root.title('root') 
login = Toplevel(root) 
login.title('login') 
root.after(3000, login.destroy) 
root.mainloop() 

TkinterSummary

All Tkinter access must be from the main thread (or, more precisely, the thread that called mainloop). Violating this is likely to cause nasty and mysterious symptoms such as freezes or core dumps.

+0

谢谢,不知道! – 72Leroy