2

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

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

但蟒蛇说AttributeError: 'PhotoImage' object has no attribute 'zoom'。这里有一个相关帖子的评论: Image resize under PhotoImage 上面 写着“PIL's PhotoImage does not implement zoom from Tkinter's PhotoImage (as well as some other methods)”。

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

4

1 回答 1

1

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

注意我只是导入Imageand ImageTk,不需要重命名为PIL_imageand PIL_imagetk,这对我来说只是令人困惑

于 2019-10-16T10:55:13.113 回答