python-3.x - 为我的浏览文件代码调整 tkinter 中的图像大小
问题描述
如何调整图像大小?这是我的代码..
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from PIL import Image, ImageTk
class Root(Tk):
def __init__(self):
super(Root, self).__init__()
self.title("Python Tkinter Dialog Widget")
self.minsize(640, 400)
self.labelFrame = ttk.LabelFrame(self, text = "Open File")
self.labelFrame.grid(column = 0, row = 1, padx = 20, pady = 20)
self.button()
def button(self):
self.button = ttk.Button(self.labelFrame, text = "Browse A File",command = self.fileDialog)
self.button.grid(column = 1, row = 1)
def fileDialog(self):
self.filename = filedialog.askopenfilename(initialdir = "/", title = "Select A File", filetype =
(("jpeg files","*.jpg"),("all files","*.*")) )
self.label = ttk.Label(self.labelFrame, text = "")
self.label.grid(column = 1, row = 2)
self.label.configure(text = self.filename)
img = Image.open(self.filename)
photo = ImageTk.PhotoImage(img)
self.label2 = Label(image=photo)
self.label2.image = photo
self.label2.grid(column=3, row=4)
root = Root()
root.mainloop()
解决方案
您可以使用Image.resize()
不保持图像纵横比的Image.thumbnail()
哪个,或者保持图像纵横比的哪个:
img = Image.open(self.filename)
imgsize = (600, 400) # change to whatever size you want
#img = img.resize(imgsize)
img.thumbnail(imgsize)
photo = ImageTk.PhotoImage(img)
推荐阅读
- processing - 加工旋转线
- python - 将循环的输出向右移动
- smartsheet-api - 使用 Smartsheet API 删除大量行
- azure - 什么 Azure Kubernetes (AKS) “超时”会断开我集群中 Pod 的进出连接?
- csv - Python:将数据写入输出文件的多列
- ios - iOS - 进入地理围栏后获取精确的 GPS 位置
- r - R foreach() - 使用 itertools 块时如何为多个输出定义组合函数?
- r - R指定一个月中的哪一周
- java - Aspose DataSet.readXml 产生更复杂的结构
- javascript - 怎么没有弹出提示?我需要帮助设置变量以从提示输入