Home > Software engineering >  Tkinter will only display the first photo I select via filedialog.askopenfilename
Tkinter will only display the first photo I select via filedialog.askopenfilename

Time:03-07

I have a program that allows the user to select an image from their PC and then displays it. The problem is that it only works once. The first photo is displayed but if I select/open another, I would think that this photo would then appear on top of the original but it doesn't.

Any idea why?

root = tk.Tk()
root.geometry("500x500")
root.title('Color Comparer')
picture_chooser_btn = tk.Button(master=root, text='Select Image', command= lambda: open_image())
picture_chooser_btn.pack()
base_color_picker_btn = tk.Button(master=root, text='Choose Base Color', command= lambda: selectBaseColor())
base_color_picker_btn.pack()
canvas = Canvas(root, width=80, height=50, bg="#F8F9F9")

base_color_rect = canvas.create_rectangle(0, 0, 85, 85, fill="red")
canvas_label = canvas.create_text((42, 20), text="Base Color")

canvas.pack()
label = tk.Label(root, anchor="w")
label.pack(side="top", fill="x") 
root.bind('<ButtonPress-1>', on_click)

root.mainloop()

The function used to grab the photo from PC:

def open_image():
    global image_selected
    path=filedialog.askopenfilename(filetypes=[("Image File",'.jpg .png .jpeg')])
    im = Image.open(path)
    im = im.resize((400, 400), Image.ANTIALIAS)
    tkimage = ImageTk.PhotoImage(im)
    myvar=Label(root,image = tkimage)
    myvar.image = tkimage
    myvar.pack()
    myvar.lift()
    label.configure(text="you selected an image")
    print("you selected an image")
    print(str(tkimage))
    image_selected = True

CodePudding user response:

You need to destroy the old label widget containing the previous image before you can display a new one.

I made some minor modifications to your function that allows the code to work as you described

myvar = None

def open_image():
    global myvar
    if myvar is not None:
        myvar.destroy()
    path=filedialog.askopenfilename(filetypes=[("Image File",'.jpg .png .jpeg')])
    im = Image.open(path)
    im = im.resize((400, 400), Image.ANTIALIAS)
    tkimage = ImageTk.PhotoImage(im)
    myvar=Label(root,image = tkimage)
    myvar.image = tkimage
    myvar.pack()
    myvar.lift()
    label.configure(text="you selected an image")
    print("you selected an image")
    print(str(tkimage))
  • Related