2013-08-22 51 views
7

我似乎無法讓我的PIL圖像在畫布上工作。代碼:如何在畫布上打開Tkinter中的PIL圖像

from Tkinter import* 
import Image, ImageTk 
root = Tk() 
root.geometry('1000x1000') 
canvas = Canvas(root,width=999,height=999) 
canvas.pack() 
image = ImageTk.PhotoImage("ball.gif") 
imagesprite = canvas.create_image(400,400,image=image) 
root.mainloop() 

錯誤:

Traceback (most recent call last): 
    File "C:/Users/Mark Malkin/Desktop/3d Graphics Testing/afdds.py", line 7, in <module> 
    image = ImageTk.PhotoImage("ball.gif") 
    File "C:\Python27\lib\site-packages\PIL\ImageTk.py", line 109, in __init__ 
    mode = Image.getmodebase(mode) 
    File "C:\Python27\lib\site-packages\PIL\Image.py", line 245, in getmodebase 
    return ImageMode.getmode(mode).basemode 
    File "C:\Python27\lib\site-packages\PIL\ImageMode.py", line 50, in getmode 
    return _modes[mode] 
KeyError: 'ball.gif' 

我需要使用PIL圖像不PhotoImages因爲我想調整我的圖片。請不要建議切換到Pygame,因爲我想使用Tkinter。

+1

我很困惑 - 你說你不想使用'PhotoImage's,但你的代碼使用'PhotoImage'。你的意思是你想使用'ImageTk.PhotoImage'而不是'Tkinter.PhotoImage'? – Brionius

+1

你有沒有試過閱讀'PhotoImage'的文檔?它需要一個圖像對象,或者一個模式和一個尺寸。你也沒有通過它;你傳遞一個文件名。 ('return _modes [mode]'上的'KeyError'很明顯它試圖將文件名視爲一種模式...但是嘗試使用哪一個並不重要,它會以任何方式失敗。) – abarnert

回答

8

先嚐試創建一個PIL圖像,然後使用它來創建PhotoImage。

from Tkinter import * 
import Image, ImageTk 
root = Tk() 
root.geometry('1000x1000') 
canvas = Canvas(root,width=999,height=999) 
canvas.pack() 
pilImage = Image.open("ball.gif") 
image = ImageTk.PhotoImage(pilImage) 
imagesprite = canvas.create_image(400,400,image=image) 
root.mainloop() 
+0

ImageTk.PhotoImage是我想用的,因爲我想成爲一個能夠調整大小的東西。 – user164814

+0

raise ImportError(「_imaging C模塊沒有安裝」) ImportError:_imaging C模塊沒有安裝 – user164814

+0

@ user164814啊,你在那裏玩得很開心。你錯過了PIL二進制文件 - 這是PIL安裝的問題,而不是代碼。請參閱[本文](http://effbot.org/zone/pil-imaging-not-installed.htm)。如果您使用MacPorts安裝PIL,請嘗試自己安裝系統版本。祝你好運。 – Brionius

2

您可以導入多種圖像格式,並使用此代碼調整大小。 「底寬」設置圖像的寬度。

from Tkinter import * 
import PIL 
from PIL import ImageTk, Image 

root=Tk() 
image = Image.open("/path/to/your/image.jpg") 
canvas=Canvas(root, height=200, width=200) 
basewidth = 150 
wpercent = (basewidth/float(image.size[0])) 
hsize = int((float(image.size[1]) * float(wpercent))) 
image = image.resize((basewidth, hsize), PIL.Image.ANTIALIAS) 
photo = ImageTk.PhotoImage(image) 
item4 = canvas.create_image(100, 80, image=photo) 

canvas.pack(side = TOP, expand=True, fill=BOTH) 
root.mainloop() 
0

(一個老問題,但答案迄今只完成了一半)

閱讀文檔:

class PIL.ImageTk.PhotoImage(image=None, size=None, **kw) 
  • image - 無論是PIL圖像,或模式字符串。 [...]
  • file - 從(使用Image.open(file))加載圖像的文件名。

所以,在你的榜樣,用

image = ImageTk.PhotoImage(file="ball.gif") 

或明確

image = ImageTk.PhotoImage(Image("ball.gif")) 

(請記住 - 因爲你做了正確的:保持在你的Python程序中的圖像對象的引用,否則它是垃圾收集之前,你seee)。

相關問題