本文介绍了如何从 Python 3 的 tkinter 文件对话框中获取字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm attempting to use the tkinter filedialog to get the user's choice of a file in my Python 3.4 program.

以前,我试图使用 Gtk FileChooserDialog,但我不断地撞墙让它工作(这是我的问题.)所以,我(尝试)切换到 tkinter 并使用文件对话框.

Previously, I was trying to use the Gtk FileChooserDialog, but I keep running into wall after wall getting it to work (here's my question about that.) So, I (attempted to) switched over to tkinter and use the filedialog.

这是我用于 GUI 的代码:

Here's the code I'm using for the 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

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

It works perfectly, except for the fact that it returns an <class '_io.TextIOWrapper'> object instead of a string, like I expected/need it to.

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

Calling str() on that doesn't work, and neither does using the io module function getvalue().

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

Does anyone know how I could get the chosen file path as a string from the filedialog.askopenfile() function?

推荐答案

我确定有几种方法,但是如何获取 path.name 呢?这应该是一个字符串.

I'm sure there are several ways, but what about getting path.name? This should be a string.

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 代替.请参阅链接了解更多信息:

Note that askopenfile opens and returns the file in read mode by default. If you just want the filename and plan on opening it yourself later, try using askopenfilename instead. See this link for more:

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

这篇关于如何从 Python 3 的 tkinter 文件对话框中获取字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 08:56