How do I make lines by clicking, dragging and releasing the mouse on Tkinter?
I think the easiest way to achieve what you want is to create a line when you click, then change the coordinates while dragging and keep it when you release.If you simply make a new line for every click and update the coordinates on drag, you don't even need the release event:
import Tkinter as tkroot = tk.Tk()canvas = tk.Canvas(root, bg="white", width=600, height=400)canvas.pack()coords = {"x":0,"y":0,"x2":0,"y2":0}# keep a reference to all lines by keeping them in a list lines = []def click(e): # define start point for line coords["x"] = e.x coords["y"] = e.y # create a line on this point and store it in the list lines.append(canvas.create_line(coords["x"],coords["y"],coords["x"],coords["y"]))def drag(e): # update the coordinates from the event coords["x2"] = e.x coords["y2"] = e.y # Change the coordinates of the last created line to the new coordinates canvas.coords(lines[-1], coords["x"],coords["y"],coords["x2"],coords["y2"])canvas.bind("<ButtonPress-1>", click)canvas.bind("<B1-Motion>", drag) root.mainloop()
In this solution you will be able to draw lines and get its coordinates too
import tkinter as tkroot = tk.Tk()canvas = tk.Canvas(root, bg="white", width=600, height=400)canvas.pack()coords = {"x":0,"y":0,"x2":0,"y2":0}final=[]lines = []def click(e): coords["x"] = e.x coords["y"] = e.y lines.append(canvas.create_line(coords["x"],coords["y"],coords["x"],coords["y"]))def release(l): lis=[] lis.append(coords["x"]);lis.append(coords["y"]);lis.append(coords["x2"]);lis.append(coords["x2"]) final.append(lis)def drag(e): coords["x2"] = e.x coords["y2"] = e.y canvas.coords(lines[-1], coords["x"],coords["y"],coords["x2"],coords["y2"])canvas.bind("<ButtonPress-1>", click)canvas.bind("<B1-Motion>", drag) canvas.bind('<ButtonRelease-1>', release)root.mainloop()print(final)
Very simple solution:
canvas = Canvas(bg="white", width=600, height=400)canvas.pack()store = {'x':0,"y":0,"x2":0,"y2":0} #store values in a map x,y:start x2,y2:end def click(c): store['x'] = c.x store['y'] = c.ydef release(l): store['x2'] = l.x store['y2'] = l.y draw() # Release the mouse and drawdef draw(): canvas.create_line(store['x'],store['y'],store['x2'],store['y2'])canvas.bind('<ButtonPress-1>', click)canvas.bind('<ButtonRelease-1>', release)mainloop()