Bhaskar pal
Bhaskar pal

Reputation: 154

How to overwrite an image in Tkinter

I created a simple image opening program which opens the image selected from filedialog by clicking a button, but wherever I select another image it just appears under the current image

I want the next image selected to be replaced by the old image.

Plz help what should I do

from tkinter import *
from PIL import Image,ImageTk
from tkinter import filedialog

root=Tk()
root.title('Image')

def open():
    global my_img
    root.filename = filedialog.askopenfilename(initialdir='/GUI',title='Select A File',filetypes=(('jpg files','*.jpg'),('png files','*.png'),('all files','*.*')))
    my_img = ImageTk.PhotoImage(Image.open(root.filename))
    my_image_lbl = Label(image=my_img).pack()
    
my_btn = Button(root,text='Open File Manager',command=open).pack()

root.mainloop()

Upvotes: 1

Views: 501

Answers (1)

acw1668
acw1668

Reputation: 46669

You should create the my_image_lbl outside open() and update its image inside the function:

from tkinter import *
from PIL import Image,ImageTk
from tkinter import filedialog

root=Tk()
root.title('Image')

def open():
    filename = filedialog.askopenfilename(initialdir='/GUI',title='Select A File',filetypes=(('jpg files','*.jpg'),('png files','*.png'),('all files','*.*')))
    if filename:
        my_image_lbl.image = ImageTk.PhotoImage(file=filename)
        my_image_lbl.config(image=my_image_lbl.image)
    
Button(root,text='Open File Manager',command=open).pack()

my_image_lbl = Label(root)
my_image_lbl.pack()

root.mainloop()

Upvotes: 4

Related Questions