[英]How can I use askopenfile to get a valid filename
I'm trying to create a program with Tkinter and tkFileDialog that opens a file for reading and then packs it into a text widget but, whenever I run this: 我正在尝试使用Tkinter和tkFileDialog创建一个程序,该程序打开一个文件以供读取,然后将其打包到文本小部件中,但是每当运行此命令时:
from Tkinter import *
from tkFileDialog import askopenfile
import time
m = Tk()
def filefind():
file = askopenfile()
f = open(str(file), "r+")
x = f.read()
t = Text(m)
t.insert(INSERT, x)
t.pack()
b = Button(m, text='File Picker', command=filefind)
b.pack()
m.mainloop()
I get this: 我得到这个:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in __call__
return self.func(*args)
File "C:\Users\super\PycharmProjects\untitled1\File Picker.py", line in filefind
f = open(str(file), "r+")
IOError: [Errno 22] invalid mode ('r+') or filename: "<open file u'C:/Users/super/PycharmProjects/untitled1/util.h', mode 'r' at 0x00000000026E0390>"
Here is the issue; 这是问题所在; askopenfile()
is returning an object, not just the name. askopenfile()
返回一个对象,而不仅仅是名称。 If you print file
, you will get <_io.TextIOWrapper name='/File/Path/To/File.txt' mode='r' encoding='UTF-8'>
. 如果您打印file
,则将得到<_io.TextIOWrapper name='/File/Path/To/File.txt' mode='r' encoding='UTF-8'>
。 You want the name=
from the object. 您需要对象的name=
。 To get that, all you need to do is replace f = open(str(file), "r+")
with f = open(file.name, "r+")
. 为此,您要做的就是将f = open(str(file), "r+")
替换为f = open(file.name, "r+")
。
Here is how it will look in your code: 这是代码中的样子:
from Tkinter import *
from tkFileDialog import askopenfile
import time
m = Tk()
def filefind():
file = askopenfile()
f = open(file.name, "r+") # This will fix the issue.
x = f.read()
t = Text(m)
t.insert(INSERT, x)
t.pack()
b = Button(m, text='File Picker', command=filefind)
b.pack()
m.mainloop()
Edit 编辑
A cleaner way of doing this is by letting askopenfile()
do the work of opening a file instead of 're-opening' it again with open()
. 一种更干净的方法是让askopenfile()
完成打开文件的工作,而不是使用open()
再次“重新打开”文件。 Here is the cleaner version: 这是更干净的版本:
file = askopenfile()
x = file.read()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.