特金特文件对话框.askopenfilename()窗口在python 3中无法关闭

2024-09-30 06:30:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python2x中玩tkinter,每当我使用filename = tkFileDialog.askopenfilename()时,我可以轻松地打开一个文件供使用,然后对话框窗口自动关闭。在

不知何故,这在python3x中不起作用

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按钮时,它会冻结并迫使我用任务管理器关闭它。在

有什么办法吗?提前谢谢!在


Tags: 文件ofimporttkinterfilenamedictinfilereader
1条回答
网友
1楼 · 发布于 2024-09-30 06:30:47

您需要创建一个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()

相关问题 更多 >

    热门问题