Skip to main content
 首页 » 编程设计

python之如何在 Tkinter 中将图像 (.png) 放置在 `LabelFrame` 中并调整其大小

2024年10月24日12zengkefu

我正在尝试将 .png 图像放在 Tkinter 窗口的 LabelFrame 中。我导入了 PIL,所以应该支持 .png 图像类型(对吗?)。我似乎无法显示图像。

这是我修改后的代码:

import Tkinter 
from Tkinter import * 
from PIL import Image, ImageTk 
 
root = Tk() 
 
make_frame = LabelFrame(root, text="Sample Image", width=150, height=150) 
make_frame.pack() 
 
 
stim = "image.png" 
width = 100 
height = 100 
stim1 = stim.resize((width, height), Image.ANTIALIAS) 
img = ImageTk.PhotoImage(image.open(stim1)) 
in_frame = Label(make_frame, image = img) 
in_frame.pack() 
 
root.mainloop() 

使用这段代码,我得到了一个 AttributeError,内容为:“'str' 没有属性 'resize'”

请您参考如下方法:

@米奇,

您必须在 PIL.Image 对象上调用 .resize 方法,而不是文件名,它是一个字符串。此外,您可能更喜欢使用 PIL.Image.thumbnail 而不是 PIL.Image.resize,原因描述得很清楚 here .您的代码很接近,但这可能是您需要的:

import Tkinter 
from Tkinter import * 
from PIL import Image, ImageTk 
 
root = Tk() 
 
make_frame = LabelFrame(root, text="Sample Image", width=100, height=100) 
make_frame.pack() 
 
stim_filename = "image.png" 
 
# create the PIL image object: 
PIL_image = Image.open(stim_filename) 
 
width = 100 
height = 100 
 
# You may prefer to use Image.thumbnail instead 
# Set use_resize to False to use Image.thumbnail 
use_resize = True 
 
if use_resize: 
    # Image.resize returns a new PIL.Image of the specified size 
    PIL_image_small = PIL_image.resize((width,height), Image.ANTIALIAS) 
else: 
    # Image.thumbnail converts the image to a thumbnail, in place 
    PIL_image_small = PIL_image 
    PIL_image_small.thumbnail((width,height), Image.ANTIALIAS) 
 
# now create the ImageTk PhotoImage: 
img = ImageTk.PhotoImage(PIL_image_small) 
in_frame = Label(make_frame, image = img) 
in_frame.pack() 
 
root.mainloop()