Home > Software design >  is it possible to hold canvas.create_image images in a list? If so, how?
is it possible to hold canvas.create_image images in a list? If so, how?

Time:10-29

When I append more than one canvas.create_image images in a list then it shows the last image in the list and ignores the rest of the images that I put down. When I get the types of the elements of the list it just returns int as well.

from PIL import Image
from PIL import ImageTk
import tkinter as tk

canvasImageList = []
canvas = tk.Canvas(root, width = 640,height =640)

img = Image.open(imgDirectory)
img = img. resize((170,170), Image.ANTIALIAS)
photoImg = ImageTk.PhotoImage(img)
canvasImageList.append(canvas.create_image(100,100, image = photoImg))
#works so far


img2 = Image.open(imgDirectory2)
img2 = img2. resize((170,170), Image.ANTIALIAS)
photoImg2 = ImageTk.PhotoImage(img2)
canvasImageList.append(canvas.create_image(100,100, image = photoImg2))
#but if you add a second image to the list the first image on the canvas dissapears but the second image still remains

print(canvasImageList)
#and if you print the list it'll print
# [1,2]


print(type(canvasImageList[0]))
#and if you get the type of an element in the list then it'll return int

am I just being dumb?

CodePudding user response:

You are putting images in same position in the canvas, so only the last one can be seen:

...
canvasImageList.append(canvas.create_image(100,100, image=photoImg))
...
canvasImageList.append(canvas.create_image(100,100, image=photoImg2)) # put at same position of photoImg
...

Change the position of one of them.

Also canvas.create_image(...) returns the item ID (an integer) which can be used later to change the item by canvas.itemconfigure(...).

For example if you want to change the image later, use:

canvas.itemconfigure(canvasImageList[0], image=another_image)

CodePudding user response:

Consider this line of code:

canvasImageList.append(canvas.create_image(100,100, image = photoImg))

create_image returns an integer identifier, not the image and not an object. You are storing this integer, not the image. To save the image you need to do it in two steps:

canvasImageList.append(photoImg)
canvas.create_image(100,100, image = photoImg)
  • Related