user1513100
user1513100

Reputation: 301

PIL and Tkinter for drawing software

I am trying to write a code that would place a point/line/whatever at the mouse coordinates, aka Paint. I am using PIL and Tkinter. The problem is I can't understand how to realise canvas update.

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()

What should be added? Maybe there are other better modules for doing it ?

Upvotes: 1

Views: 1644

Answers (1)

mmgp
mmgp

Reputation: 19221

That is going to be expensive, you need to create a new PhotoImage to reflect your modifications. Alternatively, consider drawing to the canvas without using an image. If you then need to save what was draw in the canvas you have the easy option to export it to postscript, or the harder option of storing what was drawn and reproducing it.

For the moment, here is an example that adjusts your code so it works as you intended (although I recommend the option of drawing in the canvas):

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()

Upvotes: 1

Related Questions