You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

树莓派3上PhotoImage图片缩放报错问题求助

问题原因及解决办法

错误原因

ImageTk.PhotoImage对象没有resize方法——你错误地在将图片转换为tkinter可用的PhotoImage格式后调用缩放操作,而resize是PIL原生Image对象的专属方法,必须在转换为PhotoImage之前执行缩放。

修正后的代码

from tkinter import *
from PIL import Image, ImageTk

root = Tk()
canvas = Canvas(root, width=500, height=300, bg="blue")
canvas.pack(pady=20)

# 1. 先打开图片获取PIL原生Image对象
pil_img = Image.open("/home/pi/Downloads/Picture.png")
# 2. 对PIL Image对象执行缩放操作
pil_img_resized = pil_img.resize((25, 25), Image.ANTIALIAS)
# 3. 将缩放后的Image对象转换为tkinter可用的PhotoImage
im1 = ImageTk.PhotoImage(pil_img_resized)

img1 = canvas.create_image(0, 0, anchor=NW, image=im1)
root.mainloop()

兼容说明

如果运行时提示AttributeError: module 'PIL.Image' has no attribute 'ANTIALIAS',是因为新版本PIL(9.1.0及以上)将ANTIALIAS重命名为Resampling.LANCZOS,只需把代码中的Image.ANTIALIAS替换为Image.Resampling.LANCZOS即可。

内容的提问来源于stack exchange,提问作者Bam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:35:32