Python3在Tkinter中打开带有对话框的图像

2024-09-28 22:30:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习一本书中的python3课程,它没有解释我在尝试使用对话框bog(文件资源管理器)打开图像时遇到的错误,要清楚,可以使用image.open()打开图像,但当我使用文件explore打开图像时,我得到以下结果:

"C:\Users\Yoant\Documents\Python Program\Programs\Tkinter-Course\Open File dialog box\venv\Scripts\python.exe" "C:/Users/Yoant/Documents/Python Program/Programs/Tkinter-Course/Open File dialog box/main.py"
Traceback (most recent call last):
  File "C:\Users\Yoant\Documents\Python Program\Programs\Tkinter-Course\Open File dialog box\main.py", line 16, in <module>
    my_img = ImageTk.PhotoImage(Image.open(root.filename))
  File "C:\Users\Yoant\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\Image.py", line 2900, in open
    prefix = fp.read(16)
  File "C:\Users\Yoant\AppData\Local\Programs\Python\Python39\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 246: character maps to <undefined>
# this is my code below:

from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image

root = Tk()
root.title("File Dialog box")

# Return the name and location of the file.
root.filename = filedialog.askopenfile(initialdir="/Pictures", title="select a file", filetypes=(("png files", "*.jpg"),("all file", "*.*")))

# Display dir of file selected
my_lbl = Label(root, text=root.filename).pack()

# Display image
my_img = ImageTk.PhotoImage(Image.open(root.filename))
my_lbl2 = Label(image=my_img).pack()

mainloop()

Tags: inpy图像imageboxmyrootopen