如何从 Python 3 中的 tkinter 文件对话框中获取字符串?

How to get a string from the tkinter filedialog in Python 3?

我正在尝试使用 tkinter filedialog 让用户在我的 Python 3.4 程序中选择一个文件。

以前,我曾尝试使用 Gtk FileChooserDialog,但我一直 运行 一个接一个地让它工作 (。) 所以,我 ( 尝试to) 切换到 tkinter 并使用文件对话框。

这是我用于 GUI 的代码:

import tkinter
from tkinter import filedialog

root = tkinter.Tk()
root.withdraw()

path = filedialog.askopenfile()

print(type(path)) # <- Not actually in the code, but I've included it to show the type

它工作得很好,除了它 returns 一个 <class '_io.TextIOWrapper'> 对象而不是一个字符串,就像我 expected/need 那样。

调用 str() 无效,使用 io 模块函数 getvalue().

也无效

有谁知道如何从 filedialog.askopenfile() 函数中获取所选文件路径作为字符串?

我敢肯定有几种方法,但是如何获得 path.name?这应该是一个字符串。

print("type(path):", type(path))
# <class '_io.TextIOWrapper'>

print("path:", path)
# <_io.TextIOWrapper name='/some/path/file.txt' mode='r' encoding='UTF-8'>

print("path.name:", path.name)
# /some/path/file.txt

print("type(path.name):", type(path.name))
# <class 'str'>

请注意,askopenfile 默认情况下以读取模式打开文件,returns 文件。如果您只想要文件名并计划稍后自己打开它,请尝试使用 askopenfilename。有关更多信息,请参阅 this link:

First you have to decide if you want to open a file or just want to get a filename in order to open the file on your own. In the first case you should use tkFileDialog.askopenfile() in the latter case tkFileDialog.askopenfilename().