我正在尝试将{.png图像放在LabelFrame
窗口的Tkinter
内。我导入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'”
答案 0 :(得分:2)
@Mickey,
您必须在.resize
对象上调用PIL.Image
方法,而不是文件名,这是一个字符串。此外,您可能更愿意使用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()