使用PIL调整tkinter图像大小

时间:2017-08-20 05:10:34

标签: image tkinter resize python-imaging-library

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,我该怎么做才能修改上面的片段(或重做它)来实现这个不那么雄心勃勃的目标?假设我有一个最小/最大尺寸为250x350 / 375x525的窗口。图像保持相同的大小但是被剪切掉并且无法看到整个图像,只能看到窗口大小的图像部分。有没有办法修改图像的大小而不必直接在其他软件中更改实际图像?在此先感谢,并问我是否与您输入的内容相混淆。

1 个答案:

答案 0 :(得分:1)

这是你的代码改进了:

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