Unable to add image to customtkinter button

Question:

im trying to learn tkinter + customtkinter while creating a small project. I have taken bits and pieces of my code from multiple places.While trying to add an image to a ctkinter button, the following error pops up:
Given image is not CTkImage but <class ‘PIL.ImageTk.PhotoImage’>. Image can not be scaled on HighDPI displays, use CTkImage instead.

Code:

import tkinter
import customtkinter
from PIL import Image,ImageTk

customtkinter.set_appearance_mode("System")  # Modes: system (default), light, dark
customtkinter.set_default_color_theme("blue")  # Themes: blue (default), dark-blue, green

app = customtkinter.CTk()  # create CTk window like you do with the Tk window
wdth = app.winfo_screenwidth()
hgt = app.winfo_screenheight()
app.geometry("%dx%d"%(wdth,hgt))

def button_function():
    print("button pressed")

img1=ImageTk.PhotoImage(Image.open(r"C:UsersVedantDesktoppy projectpizzalogo-removebg-preview.png"))

# Use CTkButton instead of tkinter Button

button = customtkinter.CTkButton(master=app,image = img1, text="",width=500,height=200, command=button_function,compound='left')
button.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER)

app.mainloop()

I expected the image to appear inside the button

Asked By: DarkKnight263

||

Answers:

use customtkinter.CTkImage not ImageTk.PhotoImage.

Try this.


import tkinter
import customtkinter
from PIL import Image,ImageTk

customtkinter.set_appearance_mode("System")  # Modes: system (default), light, dark
customtkinter.set_default_color_theme("blue")  # Themes: blue (default), dark-blue, green

app = customtkinter.CTk()  # create CTk window like you do with the Tk window
wdth = app.winfo_screenwidth()
hgt = app.winfo_screenheight()
app.geometry("%dx%d"%(wdth,hgt))

def button_function():
    print("button pressed")

img1=customtkinter.CTkImage(Image.open(r"C:UsersVedantDesktoppy projectpizzalogo-removebg-preview.png"))

# Use CTkButton instead of tkinter Button

button = customtkinter.CTkButton(master=app,image = img1, text="",width=500,height=200, command=button_function,compound='left')
button.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER)

app.mainloop()
Answered By: codester_09

PIL was discontinued correct? now is pillow.

Answered By: Luiz Spies
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.