努力在 Tkinter 中调整图像大小

Struggling to resize an image within Tkinter

我已经为我的 Sixth Form Computing class 开发了一款基于控制台的冒险游戏,现在想将其迁移到 Tkinter。这样做的主要原因是我可以使用图片,主要是来自 game-icons.net.

的图片

到目前为止还不错,但是图像质量太高以至于当我显示它们时它们显得很大。这是一个例子:

该代码使用 for 循环来遍历当前区域(玩家所在区域)中的项目列表。这是代码:

if len(itemKeys) > 0:
    l = Label(lookWindow, text="Looking around, you see the following items....\n").pack()
    for x in range(0, len(itemKeys)):
        icon = PhotoImage(file=("icons\" + itemKeys[x] + ".png"))
        l = Label(lookWindow, image=icon)
        l.photo = icon
        l.pack()
        l = Label(lookWindow, text=("" + itemKeys[x].title())).pack()
        l = Label(lookWindow, text=("   " + locations[position][2][itemKeys[x]][0] + "\n")).pack()

else:
    l = Label(lookWindow, text="There's nothing at this location....").pack()

("icons\" + itemKeys[x] + ".png") 的部分只是进入游戏目录中的 icons 文件夹并将文件名串在一起,在这种情况下会导致 "key.png" 因为项目我们'目前正在看的是一把钥匙。

但是,现在我想调整图像的大小。我试过使用 PIL(人们说它已被弃用,但我设法安装得很好?)但到目前为止运气不好。

感谢任何帮助。 杰克

编辑: 问题已经被标记为重复了,不过我已经tried to use it了,但是回答的人好像打开了一个文件,保存为“.ppm”(?)文件然后显示出来,但是当我尝试我得到一个巨大的错误,说我无法显示 "PIL.Image.Image".

编辑 2: 更改为:

im_temp = PILImage.open(("icons\" + itemKeys[x] + ".png")).resize((250,250), PILImage.ANTIALIAS)
photo = PhotoImage(file=im_temp)
label = Label(lookWindow, image=photo)
label.photo = photo
label.pack()

现在得到这个:

您可以在将它们与您的应用程序绑定之前对其进行预处理,而不是即时调整这些巨大图像的大小。我拍摄了 'key' 和 'locked chest' 图像并将它们放在 'icons' 子目录中,然后 运行 此代码:

from PIL import Image
import glob

for infn in glob.glob("icons/*.png"):
    if "-small" in infn: continue
    outfn = infn.replace(".png", "-small.png")
    im = Image.open(infn)
    im.thumbnail((50, 50))
    im.save(outfn)

它创建了 'key-small.png' 和 'locked-chest-small.png',您可以在您的应用程序中使用它们来代替原始图像。

对于 python 2 你可以做这样的事情,它应该适用于 python 3 以及导入

的小改动后
from tkinter import Tk, Label
from PIL import Image, ImageTk

root = Tk()

file = 'plant001.png'

image = Image.open(file)

zoom = 0.5

#multiple image zise by zoom
pixels_x, pixels_y = tuple([int(zoom * x)  for x in image.size])

img = ImageTk.PhotoImage(image.resize((pixels_x, pixels_y))) # the one-liner I used in my app
label = Label(root, image=img)
label.image = img # this feels redundant but the image didn't show up without it in my app
label.pack()

root.mainloop()