我在 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/