【问题标题】:How to get a string from the tkinter filedialog in Python 3?如何从 Python 3 中的 tkinter 文件对话框中获取字符串?
【发布时间】:2015-05-01 15:47:50
【问题描述】:

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

以前,我尝试使用 Gtk FileChooserDialog,但我不断地碰壁,让它工作 (here's my question about that.) 所以,我(尝试)切换到 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

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

调用str() 不起作用,使用io 模块函数getvalue() 也不起作用。

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

【问题讨论】:

    标签: python user-interface tkinter


    【解决方案1】:

    我确定有几种方法,但是获得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 默认以读取模式打开并返回文件。如果您只想要文件名并计划稍后自己打开它,请尝试改用askopenfilename。更多信息请见this链接:

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

    【讨论】:

    • 太棒了!我错过了您需要使用askopenfilename 而不仅仅是askopenfile。 +1 接受 :)
    • 我犯了同样的错误。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    相关资源
    最近更新 更多