Reputation: 41
I would like to delete a line drawn on canvas using Tkinter/Python with a mouse click.
This code draws the line as object, and then immediately deletes it:
#!/usr/bin/python
from Tkinter import *
master = Tk()
w = Canvas(master, width=200, height=200)
w.pack()
i=w.create_line(0, 0, 100, 100)
w.delete(i)
mainloop()
What would the code be to do the line deletion on mouse click (left or right button doesn't matter) ?
Thanks.
Upvotes: 0
Views: 2798
Reputation: 41
from Tkinter import *
import math
master = Tk()
w = Canvas(master, width=200, height=200)
w.pack()
x1=0
y1=0
x2=100
y2=100
delta=10
i=w.create_line(x1, y1, x2, y2)
def click(event):
# event.x is the x coordinate and event.y is the y coordinate of the mouse
D = math.fabs((event.y-event.x))/math.sqrt(2)
if D < delta and x1 - delta < event.x < x2 + delta:
w.delete(i)
w.bind("<Button-1>", click)
mainloop()
Upvotes: 0
Reputation:
This will do it:
from Tkinter import *
master = Tk()
w = Canvas(master, width=200, height=200)
w.pack()
i=w.create_line(0, 0, 100, 100)
# Bind the mouse click to the delete command
w.bind("<Button-1>", lambda e: w.delete(i))
mainloop()
Edit in response to comment:
Yes, the above solution will register a mouse click anywhere in the window. If you want it to only delete the line if the click is close to it, you will need something more complex. Namely, something like this:
from Tkinter import *
master = Tk()
w = Canvas(master, width=200, height=200)
w.pack()
i=w.create_line(0, 0, 100, 100)
def click(event):
# event.x is the x coordinate and event.y is the y coordinate of the mouse
if 80 < event.x < 120 and 80 < event.y < 120:
w.delete(i)
w.bind("<Button-1>", click)
mainloop()
This script will delete the line only if the x
and y
coordinates of the mouse click are withing 20 points of the line.
Note that I cannot perfectly set this. You will have to tweak it to your needs.
Upvotes: 1