-1

Recently I am working on a project text editor using Tkinter library of Python. I tried to make a function to insert image in text area.

def insertImage():
    select_image = filedialog.askopenfilename(title="Select your image",filetypes=[("Image Files", "*.png"), ("Image Files", "*.jpg")])
    global img
    img = ImageTk.PhotoImage(file=select_image)
    content_text.image_create(END, image=img)

It works fine when I tried to insert first image but when I insert the second image in Editor, the first image become invisible or white

First image Second image

I have imported all necessary libraries like tkinter, filedialog, PIL,etc. Can you please tell what are the problem in my code or could provide the correct solution. Thanks in Advance!!

Tanishka
  • 401
  • 1
  • 6
  • 22

1 Answers1

0

It is because you have used same global variable img for the images. When new image is selected and assigned to img, then there is no variable referencing the previous image and so it will be garbage collected.

Use a list to store the open images instead:

imagelist = []

def insertImage():
    select_image = filedialog.askopenfilename(title="Select your image",filetypes=[("Image Files", "*.png"), ("Image Files", "*.jpg")])
    if select_image:
        imagelist.append(ImageTk.PhotoImage(file=select_image))
        content_text.image_create(tk.END, image=imagelist[-1])
acw1668
  • 40,144
  • 5
  • 22
  • 34