首页 > 解决方案 > 调整图像大小 Python Tkinter

问题描述

您好,我在调整图片大小时遇到​​问题。我正在尝试调整图像大小以适合蓝色绘图。但是我这样做的方式会返回错误。

File "gui.py", line 42, in fileDialog
self.display = Label(image=self.photo.resize((800, 600),Image.ANTIALIAS))
AttributeError: 'PhotoImage' object has no attribute 'resize

我只是在测试它是否适合做 800,600 我真的不知道。

def fileDialog(self):
    self.filename = filedialog.askopenfilename(title="Select")
    self.label = ttk.Label(self.labelFrame, text="")
    self.label.grid(column=1, row=2)
    self.label.configure(text=self.filename)
    self.photo= ImageTk.PhotoImage(file = self.filename)
    self.display = Label(image=self.photo.resize((800, 600),Image.ANTIALIAS))
    self.display.grid(row=0)

在蓝色绘图中插入图像

有什么我做错了吗?请指教。

标签: pythontkinter

解决方案


您需要调整图像的大小,而不是照片图像。

import tkinter as tk
from PIL import Image, ImageTk

filename = 'bell.jpg'
img = Image.open(filename)
resized_img = img.resize((200, 100))

root = tk.Tk()
root.photoimg = ImageTk.PhotoImage(resized_img)
labelimage = tk.Label(root, image=root.photoimg)
labelimage.pack()

在此处输入图像描述

要解决新问题,您不必在创建标签时知道文件名。以下代码产生相同的结果:

import tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
labelimage = tk.Label(root)
labelimage.pack()

filename = 'bell.jpg'
img = Image.open(filename)
resized_img = img.resize((200, 100))
root.photoimg = ImageTk.PhotoImage(resized_img)
labelimage.configure(image=root.photoimg)

推荐阅读