Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.read()返回";unicode对象没有属性“读取”;使用askopenfilename()在python中_Python_Unicode_Tkinter_Attributeerror - Fatal编程技术网

.read()返回";unicode对象没有属性“读取”;使用askopenfilename()在python中

.read()返回";unicode对象没有属性“读取”;使用askopenfilename()在python中,python,unicode,tkinter,attributeerror,Python,Unicode,Tkinter,Attributeerror,我试图在Python的Tkinter中为scrolledText创建一个导入函数,但是在读取文件时,会引发AttributeError。代码: def open_command(): openfile = tkFileDialog.askopenfilename() if openfile != None: contents = openfile.read() textPad.delete('1.0', END) textPad.i

我试图在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,或者将上面的更改为<代码>打开(文件名,“R”)< /> > <代码> ASKOpenFrimeNe>代码>返回文件名“代码>”。您不能对文件名调用read()`,这正是错误告诉您的。非常感谢!切换到Python3有什么特别的原因吗?我更习惯于Python 2.7。Python 2.7在2020年后将不会被维护。Python3有很多有用的特性,较新的模块将不支持2.7。如果您使用strings/unicode做任何事情,切换将是一种彻底的解脱。