2017-04-21 75 views
0

我想导入一个png图像,但是我无法用正确的方法将imagetype作为参数写入Image函数。我试过写“PNG”,“imgtype =”PNG“,但它不会工作。是否有人知道如何正确书写。我使用下面的代码。我使用OSX btw。用PIL导入png图像时遇到麻烦

from Tkinter import * 
import PIL 

root = Tk() 
img = Image("this is where i'm supppsed to write imgtype", file="image.png") 
panel = Canvas(root) 
panel.pack(side = "bottom", fill = "both", expand = "yes") 
panel.create_image(image=img) 

root.mainloop() 

回答

0

你正试图从tkinters创建图像Image类,但它不支持.png图像。

documentation

的光象类可以从文件中读取GIF和PGM/PPM图片:

photo = PhotoImage(file="image.gif") 

如果您需要其他格式的文件工作,Python图像 库(PIL)包含的类可让您以超过30种格式加载图像,并将它们转换为与Tkinter兼容的图像对象:

from PIL import Image, ImageTk 

image = Image.open("lenna.jpg") 
photo = ImageTk.PhotoImage(image) 

这样做from Tkinter import *,您正在加载从Tkinter包中的所有模块到全局命名空间,所以Image你的情况实际上是Tkinter.Image

要解决问题,请尝试:

pil_img = PIL.Image.open("image.png") 
img = PIL.ImageTk.PhotoImage(pil_img) 
+0

谢谢,它的工作。现在我遇到了一个新问题,但是..它说_imaging C模块没有安装 – ronaldfisher

+0

我发现这篇文章在effbot.org这可能有所帮助:http://effbot.org/zone/pilimaging-not-installed。 HTM – alxwrd