我在python 2x中使用tkinter玩耍,每当我使用filename = tkFileDialog.askopenfilename()
时,我都可以轻松地打开一个文件供使用,并且对话框窗口将在之后自动关闭。
这在python 3x中不起作用。示例代码:
import tkinter
from tkinter import filedialog
def character_mentions():
filename = filedialog.askopenfilename()
with open(filename, 'r') as infile:
reader = csv.reader(infile)
dict_of_mentions = {rows[1]:rows[2] for rows in reader}
print(dict_of_mentions)
这给了我想要的输出,但是空的根窗口保持打开状态,空白。当我按下X按钮时,它冻结并迫使我使用任务管理器将其关闭。
关于在这里做什么的任何想法?预先感谢!
答案 0 :(得分:1)
您需要创建一个tkinter实例,然后隐藏主窗口。
在函数中,一旦函数完成,您就可以简单地destroy()
tkinter实例。
import tkinter
from tkinter import filedialog
root = tkinter.Tk()
root.wm_withdraw() # this completely hides the root window
# root.iconify() # this will move the root window to a minimized icon.
def character_mentions():
filename = filedialog.askopenfilename()
with open(filename, 'r') as infile:
reader = csv.reader(infile)
dict_of_mentions = {rows[1]:rows[2] for rows in reader}
print(dict_of_mentions)
root.destroy()
character_mentions()
root.mainloop()