python - tkinter filedialog.askopenfilename() 窗口在 python 3 中不会关闭

标签 python python-3.x tkinter

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

关于在这里做什么有什么想法吗?提前致谢!

最佳答案

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

关于python - tkinter filedialog.askopenfilename() 窗口在 python 3 中不会关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51595372/

相关文章:

python-3.x - 如何使用 Dash 在具有大型数据帧的数据表中提供分页

python - 如何在 python tkinter 中右键单击时将值传递给弹出命令

python - 为什么 scipy.ndimage.gaussian_filter 没有内核大小?

python - 我如何在 MySQL 中导致死锁以进行测试

python - Matplotlib 条形图中的线条

python - python 脚本的采购输出因管道异常异常而失败

python - 当我尝试将 excel 文件转换为列表时,“DataFrame”对象没有属性 'tolist'

python - 如何为文本小部件设置字符的最大宽度?

python - 从 Django 中的表名中查找模型实例

python - 提交表单后服务器返回403错误?