python - 当我通过 python 中的文件对话框打开图像时,为什么会收到“UnicodeDecodeError”?
问题描述
我是一个 python 初学者,我正在为我的学校项目编写一个程序。我的目标是使用文件对话框打开图像文件。
from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
root = Tk()
root.title("Title")
root.filename = filedialog.askopenfile(initialdir = "/Users/karan/Downloads",
title = "Select a file",
filetypes=(("png files","*.png"),("jpeg files","*.jpeg")))
my_lable = Label(root, text= root.filename)
my_image = ImageTk.PhotoImage(Image.open(root.filename))
my_image_label = Label(image = my_image)
my_image_label.pack()
root.mainloop()
当我执行这个程序时,我得到以下错误。
Traceback (most recent call last):
File "/Users/karan/Documents/filedilog box.py", line 24, in <module>
my_image = ImageTk.PhotoImage(Image.open(root.filename))
File "/Users/karan/opt/anaconda3/lib/python3.8/site-packages/PIL/Image.py", line 2977, in open
prefix = fp.read(16)
File "/Users/karan/opt/anaconda3/lib/python3.8/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
我该如何解决这个错误?
(其他细节——Python 3.8.8、Spyder IDE、Mac OS)
谢谢!阅读我的问题。