我正在尝试使用PIL的ImageDraw模块进行单独的像素操作。下面的代码应该创建Tkinter canvas小部件。然后打开图像,将一个像素的颜色更改为红色,然后将图像嵌入到画布小部件中。但是,它似乎没有起作用。
我的代码:
import Tkinter
from PIL import ImageTk, Image, ImageDraw
class image_manip(Tkinter.Tk):
def __init__(self):
Tkinter.Tk.__init__(self)
self.configure(bg='red')
self.ImbImage = Tkinter.Canvas(self, highlightthickness=0, bd=0, bg='blue')
self.ImbImage.pack()
im = Image.open(r'C:\Python26\Suite\test.png')
print im.format, im.size, im.mode
im = ImageDraw.Draw(im)
im = im.point((0, 0), fill="red")
self.i = ImageTk.PhotoImage(im)
self.ImbImage.create_image(139, 59, image=self.i)
def run():
image_manip().mainloop()
if __name__ == "__main__":
run()
运行我的代码后出现以下错误:
Exception AttributeError: "PhotoImage instance has no attribute '_PhotoImage__photo'" in <bound method PhotoImage.__del__ of <PIL.ImageTk.PhotoImage instance at 0x05DF7698>> ignored
Traceback (most recent call last):
File "<string>", line 245, in run_nodebug
File "C:\Python26\Suite\test_image.py", line 30, in <module>
run()
File "C:\Python26\Suite\test_image.py", line 28, in run
image_manip().mainloop()
File "C:\Python26\Suite\test_image.py", line 20, in __init__
self.i = ImageTk.PhotoImage(im)
File "C:\Python26\lib\site-packages\PIL\ImageTk.py", line 109, in __init__
mode = Image.getmodebase(mode)
File "C:\Python26\lib\site-packages\PIL\Image.py", line 245, in getmodebase
return ImageMode.getmode(mode).basemode
File "C:\Python26\lib\site-packages\PIL\ImageMode.py", line 50, in getmode
return _modes[mode]
KeyError: None
答案 0 :(得分:9)
您的问题是您正在为im
重新分配多个内容。
im = Image.open(r'C:\Python26\Suite\test.png')
im = ImageDraw.Draw(im)
im = im.point((0, 0), fill="red")
当您调用ImageTk.PhotoImage(im)
时,该函数需要一个PIL图像对象,但您已经为im
函数的结果分配了point()
,该函数实际返回None
}。这是导致问题的原因。
我认为你误解了ImageDraw的工作原理。看看here的例子。基本上是:
ImageDraw
的实例ImageDraw
直接描绘您在施工期间给出的图像ImageDraw
对象。它不包含任何重要信息,因为所有内容都直接写入图像。这是固定的__init__
方法:
def __init__(self):
Tkinter.Tk.__init__(self)
self.configure(bg='red')
im = Image.open(r'C:\Python26\Suite\test.png')
width, height = im.size
self.ImbImage = Tkinter.Canvas(self, highlightthickness=0, bd=0, bg='red', width=width, height=height)
self.ImbImage.pack()
print im.format, im.size, im.mode
draw = ImageDraw.Draw(im)
draw.rectangle([0, 0, 40, 40 ], fill="green")
del draw
self.i = ImageTk.PhotoImage(im)
self.ImbImage.create_image(width/2, height/2, image=self.i)
你会注意到我修复了一些事情:
ImageDraw
实例分配给单独的变量draw.rectangle
的返回值 - 它实际上会返回None
,就像大多数其他绘图函数一样。draw
变量create_image