2015-07-10 345 views
1

我試圖在Tkinter窗口中的LabelFrame中放置.png圖像。我導入了PIL,所以應該支持.png圖片類型(對吧?)。我似乎無法讓圖像顯示出來。如何在Tkinter中將圖像(.png)放入「LabelFrame」中並調整大小?

這裏是我修改後的代碼:

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,上面寫着: 「 '海峽' 有沒有屬性 '調整'」

+0

使用圖像文件的絕對路徑? –

+0

無法重現。我所做的只是將'Tkinter'改爲'tkinter'(我只爲Python 3安裝了PIL)和'image.png'作爲工作目錄中PNG文件的名稱,並且工作正常。 – TigerhawkT3

+0

我也無法重現它。它在Python 2.7.9中完美運行。你可以編輯你的文章,並添加確切的錯誤文本? – rjonnal

回答

1

@Mickey,

您必須調用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() 
+0

非常感謝!這很好。 – Mickey

相關問題