使用 PIL 调整 tkinter 图像大小

tkinter image sizing with PIL

from tkinter import *
from PIL import ImageTk, Image
import os

root = Tk()
img = ImageTk.PhotoImage(Image.open("example_image.png"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()

root.minsize(width=250, height=275)
root.maxsize(width=375, height=525)

我已经尝试了多种方法来处理它,但无论我尝试什么,图像都将保持相同的大小。为简单起见,假设图像为 400x800,我希望将图像缩放到 125x250,我将如何修改上面的代码片段(或重做)以实现这个不太雄心勃勃的目标?假设我有一个 window,min/max 大小为 250x350/375x525。图像保持相同大小但被裁剪,无法看到整个图像,只能看到图像中 window 大小的部分。有没有办法直接在其他软件中修改图片的大小,而不必直接更改实际图片?提前致谢,请问我是否将您与我输入的内容混淆了。

这是您改进后的代码:

from tkinter import *
from PIL import ImageTk, Image
import os


def change_image_size(event):
    # This function resizes original_img every time panel size changes size.
    global original_img
    global img
    global first_run
    global wid_dif
    global hei_dif
    if first_run:
        # Should get size differences of img and panel because panel is always going to a little bigger.
        # You then resize origianl_img to size of panel minus differences.
        wid_dif = event.width - img.width()
        hei_dif = event.height - img.height()
        # Should define minsize, maxsize here if you aren't
        # going to define root.geometry yourself and you want
        # root to fit to the size of panel.
        root.minsize(width=250, height=275)
        root.maxsize(width=375, height=525)
        first_run = False
    pimg = original_img.resize((event.width-wid_dif,event.height-hei_dif))
    img = ImageTk.PhotoImage(pimg)
    panel.configure(image=img)



first_run = True # first time change_image_size runs
wid_dif = 0 # width difference of panel and first unchanged img
hei_dif = 0 # height difference of panel and first unchanged img

root = Tk()

original_img = Image.open("example_image.png")
img = ImageTk.PhotoImage(original_img)
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
# This "<Configure>" runs whenever panel changes size or place 
panel.bind("<Configure>",change_image_size)
root.mainloop()