So I have a loop to make multiple canvas images on a canvas.
But when I run my code, only one image appears.
(Just assume the window is already set up as root and PIL is imported)
1 x,y = 0
2 tiles = []
3 tilesize = 32
4 gridwidth = 10
5 gridheight = 10
3 canvas=Canvas(root, width=500, height=500, bg="#800000")
4 for i in tiles:
5 image = PIL.ImageTk.PhotoImage(PIL.Image.open("tile.png").resize((tilesize, tilesize), PIL.Image.ANTIALIAS))
6 tiles.append(canvas.create_image(x*tilesize, y*tilesize, image=image, anchor=NW))
7 x+=1
8 if x%gridwidth == 0:
9 y+=1
10 x=0
11 if y == gridheight+1:
12 # Do some error handling stuff
If after this if I add print(tiles) I see a list of incrementing values, as it should be. eg:
[1, 2, 3, 4, 5...98, 99, 100]
If I run this:
13 test=[]
14 for i in tiles:
15 test.append(canvas.coords(i))
16 print(test)
I see that all the tiles have different coords, but all they show up as is one image.
My expected output is that they show up as a grid, but that does not happen.
Why is this happening, and are there any solutions?
And no, the grid function does not help for my current context.
>Solution :
Since you use same variable image for all the images created in the for loop, only the last image is referenced by image and the previous images will be garbage collected.
Use a list to store the instances of images:
...
from PIL import Image, ImageTk
...
imagelist = []
for i in range(gridwidth*gridheight):
y, x = divmod(i, gridwidth)
image = ImageTk.PhotoImage(Image.open("tile.png").resize((tilesize, tilesize), Image.ANTIALIAS))
tiles.append(canvas.create_image(x*tilesize, y*tilesize, image=image, anchor=NW))
imagelist.append(image) # save the image reference
...