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

标签 python tkinter

我正在尝试将 .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()

关于python - 如何在 Tkinter 中将图像 (.png) 放置在 `LabelFrame` 中并调整其大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31347983/

相关文章:

Python - 在列表中添加元组的元素

Python正则表达式如果单词在行中则不匹配

python - 如何在 Tkinter 列表框中插入时添加自动滚动?

linux - 使用来自另一个类的条目将项目添加到列表框

python - 来自 Tkinter Python 上顶级行为的顶级

python - 通过选中输入框将信息加载到 tkinter

python - 'e' 是格式为 '%e %B %Y' 的错误指令

Python Regex 匹配 YAML Front Matter

python - 是否有解决方法可以在单独的线程中清空事件队列?

python - 禁用 Pmw.ComboBox 小部件的输入字段