首页 > 解决方案 > 是否可以在列表中保存 canvas.create_image 图像?如果是这样,怎么做?

问题描述

当我在列表中附加多个 canvas.create_image 图像时,它会显示列表中的最后一个图像并忽略我放下的其余图像。当我获得列表元素的类型时,它也只返回 int 。

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

我只是愚蠢吗?

标签: pythontkintertkinter-canvas

解决方案


您将图像放在画布中的相同位置,因此只能看到最后一个:

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

改变其中之一的位置。

canvas.create_image(...)返回项目 ID(一个整数),稍后可以使用它来更改项目canvas.itemconfigure(...)

例如,如果您想稍后更改图像,请使用:

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

推荐阅读