我正在尝试在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()
返回文件名而不是文件对象。您需要执行以下操作:
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')
]