首页 > 解决方案 > 你可以在 Python Tkinter 中重新缩放 PhotoImage 吗?

问题描述

在我的程序中,我有两个按钮。button1调用函数 ( bt1) 在窗口中显示图像,然后删除两个按钮。button2调用函数(bt2) 我希望这个按钮显示与 button1 相同的图像,但比例因子为一半。我在想这样的事情:

scale_half_img = PhotoImage(file = 'Image.png', scale = 0.5)

当然,这不起作用,但这是我正在寻找的东西。

完整代码:

from tkinter import *
window = Tk()

def bt1():
    img = PhotoImage(file = 'Image.png')
    imglbl = Label(window, image = img, anchor = 'nw')
    imglbl.place(x = 0, y = 0, width = 865, height = 800)

    button1.destroy()
    button2.destroy()

def bt2():
    # display scaled down image

    button1.destroy()
    button2.destroy()




button1 = Button(window, text = 'Display Image', command = bt1)
button1.place(x = 10, y = 10, width = 200, height = 30)

button2 = Button (window, text = 'Display Rescaled Image', command = bt2)
button2.place(x = 10, y = 50, width = 200, height = 30)

window.mainloop()

标签: pythontkinter

解决方案


用于PIL.Image在 tkinter 中调整图像大小。你可以这样做:

from PIL import Image, ImageTk
img = Image.open('<Path to Image>')
img = img.resize((img.size[0]/2, img.size[1]/2), Image.ANTIALIAS)
resized_image = ImageTk.Photoimage(img) # use this

推荐阅读