python - 是否可以在列表中保存 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
我只是愚蠢吗?
解决方案
您将图像放在画布中的相同位置,因此只能看到最后一个:
...
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)
推荐阅读
- java - HBase 的 Bufferedmutator 中的 OutOfMemoryError
- angular - 角镖步进器
- c - 我不明白这个例子中的位移行为
- matlab - 带有表达式的单元格到matlab中的数值数组
- java - Jackson:使用 Builder 和标准 setter/getter 反序列化?
- hibernate - 尽管配置良好,@OneToMany 延迟加载仍不起作用
- java - Reactor Flux 发布方法
- f2py - 如果我想将 ifort 与 f2py 一起使用,是否需要 icc
- c# - 绑定到 MvxSpinner SelectedItem 属性不起作用
- node.js - 通过多个文件要求 socket.io 服务器时出现错误 EADDRINUSE