2

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!

Mas
  • 329
  • 2
  • 13

1 Answers1

1

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

Bruno Vermeulen
  • 2,970
  • 2
  • 15
  • 29
  • Thanks. Is there some documentation that explains why I need to use `._PhotoImage__photo`? I have no idea how I could have worked that out myself... – Mas Oct 19 '19 at 05:58
  • It took me a bit to find the method by drilling down through the __dir__ (for example `.__PhotoImage__photo.__dir__()'). As it starts with an underscore this is actually meant as a private method and discouraged for public use. – Bruno Vermeulen Oct 19 '19 at 08:18