Home > database >  Trouble with displaying images tkinter
Trouble with displaying images tkinter

Time:12-18

Images pass on top each other.

def show_ucgen():
    image = Image.open("image.png")
    image_resized = image.resize((256, 256))
    photo = ImageTk.PhotoImage(image_resized)
    label = customtkinter.CTkLabel(master,text = "", image=photo).place(x=150, y=30)
    label.pack()

    
def show_kare():
    image1 = Image.open("kare.png")
    image1_resized = image1.resize((256, 256))
    photo = ImageTk.PhotoImage(image1_resized)
    label = customtkinter.CTkLabel(master,text = "", image=photo).place(x=150, y=30)
    label.pack()


def show_daire():
    image2 = Image.open("daire.png")
    image2_resized = image2.resize((256, 256))
    photo = ImageTk.PhotoImage(image2_resized)
    label = customtkinter.CTkLabel(master,text = "", image=photo).place(x=120, y=30)
    label.pack()

Its expected to remove the image while opening another.

CodePudding user response:

You should only be using one geometry manager (pack, place, or grid) on any given widget.

Instead of:

label = customtkinter.CTkLabel(master,text = "", image=photo).place(x=150, y=30)
label.pack()

Try using only place or pack (I tend to prefer pack)

label = customtkinter.CTkLabel(master,text = "", image=photo)
label.pack()

You may want to tell the labels to expand and fill as well

#example
label.pack(expand=True, fill='both')  # 'both' meaning x and y axes

Another important note is that all of the geometry manager methods return None, so what's happening here is that each of your labels is evaluating to None. When you pack them you are trying to pack None instead of an instance of Label. For this reason, you should always instantiate your widgets separately from adding them to a geometry manager:

my_label = Label(master).pack()  # NO - my_label is now None
my_label = Label(master)
my_label.pack()  # YES - my_label is an instance of Label
  • Related