简体   繁体   中英

PhotoImage zoom

I'm trying to zoom in on an image and display it with the following code

import tkinter as tk
from PIL import Image as PIL_image, ImageTk as PIL_imagetk

window = tk.Tk()

img1 = PIL_imagetk.PhotoImage(file="C:\\Two.jpg")
img1 = img1.zoom(2)

window.mainloop()

But python says AttributeError: 'PhotoImage' object has no attribute 'zoom' . There is a comment on a related post here: Image resize under PhotoImage which says "PIL's PhotoImage does not implement zoom from Tkinter's PhotoImage (as well as some other methods)".

I think this means that I need to import something else into my code, but I'm not sure what. Any help would be great!

img1 has no method zoom , however img1._PhotoImage__photo does. So just change your code to:

import tkinter as tk
from PIL import Image as PIL_image, ImageTk as PIL_imagetk

window = tk.Tk()

img1 = PIL_imagetk.PhotoImage(file="C:\\Two.jpg")
img1 = img1._PhotoImage__photo.zoom(2)

label =  tk.Label(window, image=img1)
label.pack()

window.mainloop()

By the way if you want to reduce the image you can use the method subsample img1 = img1._PhotoImage__photo.subsample(2) reduces the picture by half.

If you have a PIL Image, then you can use resize like following example:

import tkinter as tk
from PIL import Image, ImageTk

window = tk.Tk()

image = Image.open('C:\\Two.jpg')
image = image.resize((200, 200), Image.ANTIALIAS)
img1 = ImageTk.PhotoImage(image=image)

label = tk.Label(window, image=img1)
label.pack()

window.mainloop()

Note I just import Image and ImageTk , see no need to rename to PIL_image and PIL_imagetk , which to me is only confusing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM