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

如何在Tkinter中使用PIL模块调整图片大小?报错求助

Fixing Tkinter + PIL Image Resize Errors

Hey, let's break down what's going wrong here and fix it step by step!

Why Your Code Fails

1. AttributeError: 'PhotoImage' object has no attribute 'resize'

You got the order backwards! The resize() method belongs to PIL's Image object, not ImageTk.PhotoImage. You converted the image to a Tkinter-compatible PhotoImage first, then tried to resize it—but PhotoImage doesn't have that functionality.

2. _tkinter.TclError: image "" doesn't exist

Tkinter's Label only accepts Tkinter-native image types (PhotoImage or BitmapImage). Passing a raw PIL Image object directly won't work, since Tkinter can't recognize it.

Correct Approach & Fixed Code

The right workflow is:

  • Open the image with PIL to get an Image object
  • Resize the Image object
  • Convert the resized Image to a PhotoImage
  • Pass the PhotoImage to the Label, and keep a reference to it (critical to avoid garbage collection issues)

Here's the working code:

from tkinter import Tk, Label
from PIL import Image, ImageTk

# Initialize main window
root = Tk()

# Step 1: Open image with PIL (gets an Image object)
original_img = Image.open("risinggrap.jpg")

# Step 2: Resize the Image object (use LANCZOS for high-quality scaling; ANTIALIAS is deprecated)
resized_img = original_img.resize((200, 250), Image.LANCZOS)

# Step 3: Convert resized Image to Tkinter-compatible PhotoImage
rgraph = ImageTk.PhotoImage(resized_img)

# Step 4: Create Label and assign the PhotoImage
photoLabe = Label(root, image=rgraph)
photoLabe.pack()  # Don't forget to add the Label to the window

# Critical: Keep a reference to the PhotoImage to prevent garbage collection
photoLabe.image = rgraph

# Start the Tkinter main loop
root.mainloop()

Key Notes

  • Scaling Algorithm: In modern PIL versions, Image.ANTIALIAS is deprecated—use Image.LANCZOS instead for sharper, high-quality resizing.
  • Reference Retention: Tkinter doesn't automatically hold a reference to the PhotoImage. If you don't store it (like we did with photoLabe.image = rgraph), Python's garbage collector will delete the image, and your Label will show nothing.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 21:42:30