當我在串列中附加多個 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
我只是愚蠢嗎?
uj5u.com熱心網友回復:
考慮這行代碼:
canvasImageList.append(canvas.create_image(100,100, image = photoImg))
create_image回傳一個整數識別符號,而不是影像和物件。您存盤的是這個整數,而不是影像。要保存影像,您需要分兩步完成:
canvasImageList.append(photoImg)
canvas.create_image(100,100, image = photoImg)
uj5u.com熱心網友回復:
您將影像放在畫布中的相同位置,因此只能看到最后一個:
...
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/345033.html
上一篇:如何使用包創建左、右和中心框架?
