[Python] CtkButton doesn't load images correctly

Discussão em 'Python' iniciado por Stack, Agosto 28, 2025.

  1. Stack

    Stack Membro Participativo

    I have coded a python application for help me manage my works. For do this I need some buttons. I chose to use CustomTkinter because of the visual effect but mostly of the times the icons of the buttons doesn't load. Here is my code:

    import customtkinter as ctk
    from PIL import Image
    import os
    from pathlib import Path
    import tkinter

    directory_base = Path.home() / "AppData" / "Local" / "TestApp"

    percorso_icone = os.path.join(directory_base,'Risorse','icone')
    img = Image.open(os.path.join(percorso_icone,'icona_cartelle.png'))
    cartella_con_elementi = ctk.CTkImage(light_image=img,dark_image=img,size=(40,40))

    immagini = {"cartella_con_elementi":cartella_con_elementi}

    def crea_pulsante(frame, nome, riga, colonna, resto_laterale):
    global immagini
    btn = ctk.CTkButton(master=frame,text=nome,compound='top',fg_color='white',text_color='black',corner_radius=6,cursor='hand2',hover=True)
    btn._text_label.configure(wraplength=150)
    btn.grid(row=riga, column=colonna, padx=resto_laterale, pady=5,sticky='w')
    btn.configure(image=immagini["cartella_con_elementi"])
    btn.image_associata = immagini["cartella_con_elementi"]

    print(btn.image_associata)
    return btn

    root = ctk.CTk()

    crea_pulsante(root,'test',2,5,5)

    root.mainloop()



    Here is the output: Creo pulsante: Hello -> immagine: <customtkinter.windows.widgets.image.ctk_image.CTkImage object at 0x0000024935E8C6E0> 175 35

    The size of the images is (40,40).

    I created in the same function some Labels using btn.image_associata as image and the the Label's icons were good. So I think that the problem is not related to ctkImages but to ctkButton.

    EDIT: I solved it changing this line from: btn = ctk.CTkButton(master=frame,text=nome,compound='top',fg_color='white',text_color='black',corner_radius=6,height=90,cursor='hand2',hover=True)

    to: btn = ctk.CTkButton(master=frame,text=nome,compound='top',fg_color='white',text_color='black',corner_radius=6,cursor='hand2',hover=True,image=immagini["documenti_icona"])

    in this way when I do btn.configure(image=***), I edit the image that in the previous code didn't exist

    Continue reading...

Compartilhe esta Página