Home > Enterprise >  Unable to add image to customtkinter button
Unable to add image to customtkinter button

Time:12-11

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:\Users\Vedant\Desktop\py project\pizzalogo-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

CodePudding user response:

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:\Users\Vedant\Desktop\py project\pizzalogo-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()
  • Related