python - 你可以在 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()
解决方案
用于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
推荐阅读
- c# - XmlDocument 如何将新记录插入现有 XML 文件
- plotly-dash - 已在 macOS 上安装 Dash,但在运行脚本时出错
- python - 通过文件路径运行python时出现KeyError,直接在目录中时没有问题
- linux - Linux C++ IPv6 UDP Multicast sendto 失败并出现 errno EADDRNOTAVAIL (99) 无法分配请求的地址
- javascript - jQuery选择日期时间属性大于04-01-2020的时间元素
- fortran - Fortran 编译错误 - 在函数 X 中未定义对 Y 的引用,其中函数是公共的并且已实现使用
- php - laravel - foreignId() 和 unsignedBigInteger() 之间的区别
- javascript - 如何创建 API 可以从字符串解析的 CSV?
- firefox - firefox和chrome的缓存实现有什么不同影响了twitter?
- ruby-on-rails - 使用 Ruby on Rails 处理文本搜索中的特殊字符