照片图像缩放

PhotoImage zoom

我正在尝试放大图像并使用以下代码显示它

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()

但是 python 说 AttributeError: 'PhotoImage' object has no attribute 'zoom'。这里有一个相关的 post 的评论: Image resize under PhotoImage 上面写着 "PIL's PhotoImage does not implement zoom from Tkinter's PhotoImage (as well as some other methods)".

我认为这意味着我需要将其他内容导入到我的代码中,但我不确定是什么。任何帮助都会很棒!

img1 没有方法 zoom,但是 img1._PhotoImage__photo 有。所以只需将您的代码更改为:

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()

顺便说一句,如果你想缩小图像,你可以使用方法subsample img1 = img1._PhotoImage__photo.subsample(2)将图片缩小一半。

如果您有 PIL 图像,则可以像下面的示例一样使用调整大小:

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()

注意我只是导入 ImageImageTk,不需要重命名为 PIL_imagePIL_imagetk,这对我来说只是令人困惑