2009-08-06 287 views
3

當我使用PIL加載圖像並將其顯示在Tkinter創建的窗口中時,我很想念一個非常基礎的級別。什麼我想要做的最簡單的形式是:如何與Tkinter一起使用PIL?

import Tkinter as TK 
from PIL import Image, ImageTk 

im = Image.open("C:\\tinycat.jpg") 
tkIm = ImageTk.PhotoImage(im) 
tkIm.pack() 
TK.mainloop() 

當我試圖運行上面的代碼,我得到如下:

RuntimeError: Too early to create image 
Exception AttributeError: "PhotoImage instance has no attribute 
'_PhotoImage__photo'" in <bound method PhotoImage.__del__ of 
<PIL.ImageTk.PhotoImage instance at 0x00C00030>> ignored 

我已確認該文件存在,並且可以在圖像編輯器中打開,也可以使用im.show()顯示。我錯過了什麼?

+0

可能重複的[Python Tkinter錯誤,「太早創建圖像」](http://stackoverflow.com/questions/10236857/python-tkinter-error-too-early-to-create-image) – 2013-02-27 18:23:40

回答

6

的Tkinter已被實例調用ImageTk.PhotoImage(前):

TK.Tk() 
-1

這是非常真實的東西梅雷迪思說你需要添加該行是肯定的!

我想向你展示我的圖像格式,然後把它比作你的,看看有什麼不同,我的形象代碼

master.image = PhotoImage(file="Banditlogo.gif") 
w = Label(master, image=master.image) 
w.photo = master 
w.pack() 

而且你的代碼是

im = Image.open("C:\\tinycat.jpg") 
tkIm = ImageTk.PhotoImage(im) 
tkIm.pack() 

我們都使用PIL和PhotoImage 我不禁想知道兩種方法是正確的嗎? 在這個時間點上,我沒有足夠的知識來完全回答您的PIL問題,但比較這兩個代碼是有趣的,因爲它們是不同的。我只能建議在涉及到人們與我分享的示例代碼時做我的工作,那就是「如果我的工作不成功,請嘗試示例代碼並查看是否修復了代碼」用它。

會有人對Tkinter有更多的理解請解釋一下工作原理,如何在Tkinter中使用PIL?

知識就是力量,請分享。

+0

@梅雷迪思L.帕特斯很好的回答。 – 2013-02-27 18:23:35