Python UnicodeDecodeError:&x27;charmap';编解码器可以';t解码字节0x81。如何应对
即使给定“编码='utf-8'”或甚至给出“错误='ignore'”。我也犯了同样的错误Python UnicodeDecodeError:&x27;charmap';编解码器可以';t解码字节0x81。如何应对,python,user-interface,Python,User Interface,即使给定“编码='utf-8'”或甚至给出“错误='ignore'”。我也犯了同样的错误 def open(): global My_Image root.filename = filedialog.askopenfile(initialdir = '/Users/GAURAV/Desktop', title = "Select an Image file.", filetypes = (("JPG files", "*.jpg"), ("All files", "*.*")))
def open():
global My_Image
root.filename = filedialog.askopenfile(initialdir = '/Users/GAURAV/Desktop', title = "Select an Image file.", filetypes = (("JPG files", "*.jpg"), ("All files", "*.*")))
my_label = Label(root, text = root.filename).pack()
My_Image = ImageTk.PhotoImage(Image.open(root.filename)) #over here
My_Image_Label = Label(image = My_Image).pack()
tkinter
有两个功能askopenfile
(您使用的)和askopenfilename
第二个函数(askopenfilename
)给出带有文件名的字符串
但第一个函数(askopenfile
)以文本模式打开文件,它允许访问此打开的文件,而不是其文件名
如果使用打印(键入(root.filename))
您将看到
而不是
这就产生了问题——要读取图像,需要字节模式,而不是文本模式
因此,最好使用
askopenfilename
获取文件名和Image.open()
将以字节模式打开文件并正确读取
编辑:最终您可以在
askopenfile
中使用mode=“rb”
以字节模式打开文件
root.filename = tkinter.filedialog.askopenfile(mode='rb', initialdir=..., ...)
和print(typo(root.filename))
将显示
,它还应与Image.open()配合使用
顺便说一句:当您使用askopenfile
时,您会打开文件,文件名在root.filename.name
中,这可能意味着数据不是在UTF-8
中,而是在latin1
、cp1250
或其他编码中。始终将完整的错误消息(从单词“Traceback”开始)作为问题文本(而不是注释)(不是截图)。还有其他有用的信息。最好使用askopenfilename
而不是askopenfile
,因为askopenfilename
提供文件名,而askopenfile
打开文件并给出指向此文件的指针,而不是其名称。谢谢furas。您已经提供了帮助。