.read() returns "unicode object has no attribute read" in python with askopenfilename()
.read() returns "unicode object has no attribute read" in python with askopenfilename()
我试图在 Python 的 Tkinter 中为 scrolledText 创建一个导入函数,但是在读取文件时,出现了一个 AttributeError。代码:
def open_command():
openfile = tkFileDialog.askopenfilename()
if openfile != None:
contents = openfile.read()
textPad.delete('1.0', END)
textPad.insert('1.0', contents)
openfile.close()
错误:
contents = openfile.read()
AttributeError: 'unicode' object has no attribute 'read'
我想澄清一下 'textPad' 指的是一个 'ScrolledText' 对象。
有谁知道为什么会这样?起初我以为错误可能来自编码,所以我用UTF-8编码但它仍然返回相同的错误。提前致谢!
tkFileDialog.askopenfilename()
returns 文件名不是文件对象。您需要执行以下操作:
def open_command():
filename = tkFileDialog.askopenfilename()
if filename is not None:
with open(filename) as f:
contents = f.read()
textPad.delete('1.0', END)
textPad.insert('1.0', contents)
[如果您正在使用 Python 2.7,请考虑使用 Python 3 或将以上内容更改为 open(filename, 'r')
]
我试图在 Python 的 Tkinter 中为 scrolledText 创建一个导入函数,但是在读取文件时,出现了一个 AttributeError。代码:
def open_command():
openfile = tkFileDialog.askopenfilename()
if openfile != None:
contents = openfile.read()
textPad.delete('1.0', END)
textPad.insert('1.0', contents)
openfile.close()
错误:
contents = openfile.read()
AttributeError: 'unicode' object has no attribute 'read'
我想澄清一下 'textPad' 指的是一个 'ScrolledText' 对象。 有谁知道为什么会这样?起初我以为错误可能来自编码,所以我用UTF-8编码但它仍然返回相同的错误。提前致谢!
tkFileDialog.askopenfilename()
returns 文件名不是文件对象。您需要执行以下操作:
def open_command():
filename = tkFileDialog.askopenfilename()
if filename is not None:
with open(filename) as f:
contents = f.read()
textPad.delete('1.0', END)
textPad.insert('1.0', contents)
[如果您正在使用 Python 2.7,请考虑使用 Python 3 或将以上内容更改为 open(filename, 'r')
]