Python 2.71.11 Tkinter窗口未关闭"应用程序无响应"

时间:2016-03-19 03:18:57

标签: python tkinter

我试图打开一个简单的文件对话框,要求用户选择一个文件。我的代码是:

from Tkinter import Tk
from tkFileDialog import askopenfilename

Tk().withdraw()
filename = askopenfilename()
print(filename)
sys.exit(0)

程序成功检索文件名,但窗口保持打开状态且未关闭。我退出它的唯一方法是通过Force Quit。我使用的是Mac OS X 10.11和Python 2.7.11。

谢谢

1 个答案:

答案 0 :(得分:0)

根据您的开发环境,似乎存在一些问题。见参考文献[2]。这对我有用:

from Tkinter import Tk
from tkFileDialog import askopenfilename

root = Tk() #To initialize Tkinter, we have to first create a Tk root widget
filename = askopenfilename() # store filename
# root.mainloop() may be necessary for your development environment (see [2])
root.destroy() #destroy the event loop - only required in some python environments (see [2])
print(filename)

[1] http://effbot.org/tkinterbook/tkinter-hello-tkinter.htm

[2] http://effbot.org/tkinterbook/tkinter-hello-again.htm