在Tkin中努力调整图像大小

2024-10-02 16:21:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为我的六年级计算机课程开发了一个基于控制台的冒险游戏,现在想把它移植到Tkinter中。主要原因是我可以利用图片,主要是game-icons.net的图片。

到目前为止还不错,但是图像质量很高,当我显示它们时,它们看起来非常巨大。下面是一个例子:

Problem with image size

代码的工作原理是使用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文件夹,并将一个文件名串在一起,在本例中,这将导致“键.png“因为我们目前正在查看的项目是一个关键。

不过,现在我想调整图像的大小。我试过使用PIL(人们说PIL已经过时了,但我安装得很好?)但到目前为止没有运气。

感谢任何帮助。 杰克

编辑: 这个问题已被标记为重复,但我已经tried to use it,但回答的人似乎打开了一个文件,将其另存为“.ppm”(?)文件,然后显示它,但当我尝试时,我得到一个巨大的错误,说我不能显示一个“PIL.Image.Image".

编辑2: 改为:

^{pr2}$

现在得到这个:

edit 2


Tags: 项目代码text图像forlenpilpng
2条回答

您可以在应用程序绑定它们之前对它们进行预处理,而不是动态地调整它们的大小。我把“钥匙”和“锁胸”图像放在“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)

它创造了一个'钥匙-小.png“和”锁胸-小.png,可以在应用程序中使用,而不是原始图像。在

对于python2,您可以这样做,在对import进行一些小的更改之后,它也应该适用于python3

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

相关问题 更多 >