PIL和Tkinter用于绘图软件

时间:2012-09-21 14:08:26

标签: python tkinter python-imaging-library draw paint

我正在尝试编写一个代码,可以在鼠标坐标处放置一个点/线/任何东西,也就是Paint。我正在使用PIL和Tkinter。问题是我无法理解如何实现画布更新。

window = Tk(className ='Window')
image = Image.new('RGB', (800,600),"#ffffff")

image_tk = PhotoImage(image)

canvas = Canvas(window,width = 800, height = 600)
canvas.create_image(400 ,300,image = image_tk)
canvas.pack()

draw = ImageDraw.Draw(image)


def mouseclick(event):
    draw.point((event.x,event.y),fill=128)
    print event.x,event.y

canvas.bind("<Button-1>", mouseclick)
mainloop()

应该添加什么?也许还有其他更好的模块可以做到吗?

1 个答案:

答案 0 :(得分:1)

这将是昂贵的,您需要创建一个新的PhotoImage来反映您的修改。或者,考虑在不使用图像的情况下绘制到画布。如果你需要保存画布中绘制的内容,你可以轻松选择将其导出到postscript,或者更难选择存储绘制的内容并重现它。

目前,这是一个调整代码的示例,使其按预期工作(尽管我建议在画布中绘制选项):

import Tkinter
from PIL import Image, ImageDraw, ImageTk

def paint_img(event, canvas):
    x, y = event.x, event.y
    image_draw.ellipse((x-5, y-5, x+5, y+5), fill='black')
    canvas._image_tk = ImageTk.PhotoImage(image)
    canvas.itemconfigure(canvas._image_id, image=canvas._image_tk)

root = Tkinter.Tk()

width, height = 800, 600
canvas = Tkinter.Canvas(width=width, height=height)
canvas.pack()

image = Image.new('RGB', (width, height), '#cdcdcd')
image_draw = ImageDraw.Draw(image)
canvas._image_tk = ImageTk.PhotoImage(image)
canvas._image_id = canvas.create_image(0, 0, image=canvas._image_tk, anchor='nw')
canvas.tag_bind(canvas._image_id, "<Button-1>", lambda e: paint_img(e, canvas))

root.mainloop()