0

I am writing an app where the user can "paint" a canvas and now I want to add support for shapes.
I have a canvas called paint_canvas and I want to draw a shape between the 2 points the user clicks

def draw_square(event):
    x1 = event.x
    y1 = event.y
    # now I want to get the next two points the user clicks
    # how???????
paint_canvas = Canvas(root)
paint_canvas.bind('<Button-3>', draw_square)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
IsraelW
  • 63
  • 9
  • Do you want to draw when the user presses a mouse button, drags, and then releases? Or, do you want the user to click, move the mouse, and then click a second time? – Bryan Oakley Nov 26 '20 at 10:19

2 Answers2

0

You can make two events, One for the press event ans one for release. In the first event you store x and y mouse position in another scope (startx , starty)

And in the second event you store mouse position store x and y mouse position in another scope (endx, endy) and then draw your shape with this coordinates

See : https://docstore.mik.ua/orelly/other/python/0596001886_pythonian-chp-16-sect-9.html

And : https://www.codegrepper.com/code-examples/delphi/how+to+draw+rectangle+in+tkinter

If you want to show your rect animation you can use Motion events Mouse Position Python Tkinter

NXML
  • 16
  • 2
0

You don't have to work with double-events. You can just as well store the previously clicked coordinates and draw a rectangle (and reset the previously stored coordinates) as soon as you have two clicks:

from tkinter import *


def draw_square(event):
    x1 = event.x
    y1 = event.y
    w = event.widget ## Get the canvas object you clicked on
    if w.coords == None:
        w.coords = (x1,y1)
    else:
        w.create_rectangle(w.coords[0],w.coords[1],x1,y1,fill="#ff0000")
        w.coords = None

root = Tk()
paint_canvas = Canvas(root,width=400,height=400,bg="#ffffff")
paint_canvas.pack()
paint_canvas.bind('<Button-3>', draw_square)
paint_canvas.coords=None

root.mainloop()

You could even create a temporary point to mark the first click, which may then be removed as soon as you hit the second one. This point (w.temp in the example below) can also be an attribute of the canvas, so you can access it easily via the click:

def draw_square(event):
    x1 = event.x
    y1 = event.y
    w = event.widget ## Get the canvas object you clicked on
    if w.coords == None:
        w.coords = (x1,y1)
        w.temp = w.create_oval(x1-1,y1-1,x1+1,y1+1,fill="#00ff00")
    else:
        w.create_rectangle(w.coords[0],w.coords[1],x1,y1,fill="#ff0000")
        w.delete(w.temp)
        w.coords = None
Martin Wettstein
  • 2,771
  • 2
  • 9
  • 15