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

RPi*_*ess 1 python user-interface tkinter

我正在尝试使用 tkinterfiledialog在我的 Python 3.4 程序中获取用户对文件的选择。

以前,我试图使用 Gtk FileChooserDialog,但我一直在墙后墙让它工作(这是我的问题。)所以,我(试图)切换到 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
Run Code Online (Sandbox Code Playgroud)

它工作得很好,除了它返回一个<class '_io.TextIOWrapper'>对象而不是一个字符串,就像我期望/需要的那样。

调用str()它不起作用,使用io模块 function也不起作用getvalue()

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

小智 8

我确定有几种方法,但是如何获取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'>
Run Code Online (Sandbox Code Playgroud)

请注意,askopenfile默认情况下以读取模式打开并返回文件。如果您只想要文件名并计划稍后自己打开它,请尝试使用askopenfilename。查看链接了解更多信息:

首先,您必须决定是要打开文件还是只想获取文件名以便自己打开文件。在第一种情况下,您应该在后一种情况下使用 tkFileDialog.askopenfile() tkFileDialog.askopenfilename()。