如何在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
Imageobject - Resize the
Imageobject - Convert the resized
Imageto aPhotoImage - Pass the
PhotoImageto 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.ANTIALIASis deprecated—useImage.LANCZOSinstead 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 withphotoLabe.image = rgraph), Python's garbage collector will delete the image, and your Label will show nothing.
内容的提问来源于stack exchange,提问作者user11791798
相关产品推荐
相关产品推荐

