Skip to content Skip to sidebar Skip to footer

How Do I Make Lines By Clicking, Dragging And Releasing The Mouse On Tkinter?

I'm trying to complete an exercise that asks me to draw lines in Tkinter but I don't know how I make the same canvas.create_line() receive the coordinates from different functions.

Solution 1:

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 tk

root = 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 = []

defclick(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"]))

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

Solution 2:

In this solution you will be able to draw lines and get its coordinates too

import tkinter as tk
root = 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 = []
defclick(e):
    coords["x"] = e.x
    coords["y"] = e.y
    lines.append(canvas.create_line(coords["x"],coords["y"],coords["x"],coords["y"]))

defrelease(l):
    lis=[]
    lis.append(coords["x"]);lis.append(coords["y"]);lis.append(coords["x2"]);lis.append(coords["x2"])
    final.append(lis)

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

Post a Comment for "How Do I Make Lines By Clicking, Dragging And Releasing The Mouse On Tkinter?"