【问题标题】:tkinter filedialog.askopenfilename() window won't close in python 3tkinter filedialog.askopenfilename() 窗口不会在 python 3 中关闭
【发布时间】:2019-01-06 18:53:25
【问题描述】:

我在 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 为您提供的空根窗口,无论您是否想要一个?如果您对 Tkinter 的唯一预期用途是文件或其他对话框,则最好显式创建和隐藏该根窗口:tkinter.Tk().withdraw() 也许。
  • @jasonharper 啊,是的 - 这就是我的意思,谢谢。我编辑了我的问题。我添加了那行,但很遗憾,它没有用。
  • 您的代码不完整。您缺少一个 tkinter 实例、一个主循环和对该函数的调用。请提供Minimal, Complete, and Verifiable example

标签: python python-3.x tkinter


【解决方案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()

【讨论】:

    猜你喜欢
    • 2023-02-17
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多