我正在尝试使用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()
我明白了:
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>"
答案 0 :(得分:0)
这是问题所在; askopenfile()
正在返回一个对象,而不仅仅是名称。如果您打印file
,则会获得<_io.TextIOWrapper name='/File/Path/To/File.txt' mode='r' encoding='UTF-8'>
。您需要来自对象的name=
。为此,您需要做的就是将f = open(str(file), "r+")
替换为f = open(file.name, "r+")
。
以下是代码中的内容:
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()
<强> 修改 强>
更简洁的方法是让askopenfile()
执行打开文件的工作,而不是“重新打开”。再次使用open()
。这是更清洁的版本:
file = askopenfile()
x = file.read()