I have a code which is selecting an image and displaying it on the screen:
from customtkinter import *
from PIL import ImageTk, Image
set_appearance_mode('System')
set_default_color_theme('dark-blue')
window = CTk() # Window
window.geometry("800x520")
def select_image():
filename = filedialog.askopenfile(title="Select an image", filetypes=(("png files", "*.png"), ("jpg files", "*.jpg"), ("jpeg files", "*.jpeg"), ("bmp files", "*.bmp"), ("all image files", "*.png *.jpg *.jpeg *.bmp")))
print(filename)
selected_image = ImageTk.PhotoImage(Image.open(filename))
label = CTkLabel(window, image=selected_image).place(x=0, y=0)
image_button = CTkButton(window, text="I", bg_color='white', fg_color='white', hover_color='yellow', width=25, height=25,
text_color='black', command=select_image)
image_button.place(x=425, y=10)
window.mainloop() # Loop
After I'm running my code and selecting my image I'm ruining into this problem:
<_io.TextIOWrapper name='D:/Downloads/smiling emojipng.png' mode='r' encoding='cp1251'>
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 109: character maps to <undefined>
I think something wrong is happening with incoding but I'm not sure.
The Image.open()
method receives the file path, and the filedialog.askopenfilename()
method returns the file path, so you should modify your code like this:
from customtkinter import *
from PIL import ImageTk, Image
set_appearance_mode("System")
set_default_color_theme("dark-blue")
window = CTk() # Window
window.geometry("800x520")
def select_image():
filename = filedialog.askopenfilename(
title="Select an image",
filetypes=(
("png files", "*.png"),
("jpg files", "*.jpg"),
("jpeg files", "*.jpeg"),
("bmp files", "*.bmp"),
("all image files", "*.png *.jpg *.jpeg *.bmp"),
),
)
print(filename)
selected_image = ImageTk.PhotoImage(Image.open(filename))
label = CTkLabel(window, image=selected_image).place(x=0, y=0)
image_button = CTkButton(
window,
text="I",
bg_color="white",
fg_color="white",
hover_color="yellow",
width=25,
height=25,
text_color="black",
command=select_image,
)
image_button.place(x=425, y=10)
window.mainloop() # Loop