Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I'm kinda stuck here; where and how do I put the create_line?

from Tkinter import *


canvas = Canvas(bg="white", width=600, height=400)
canvas.pack()


def click(c):
    cx=c.x
    cy=c.y
def drag(a):
    dx=a.x
    dy=a.y
def release(l):
    rx=l.x
    ry=l.y

canvas.bind('<ButtonPress-1>', click)
canvas.bind('<ButtonRelease-1>', release)
canvas.bind("<B1-Motion>", drag) 

mainloop()
like image 638
Pedro Paulo Junqueira Avatar asked Dec 22 '25 09:12

Pedro Paulo Junqueira


2 Answers

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

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()
like image 122
fhdrsdg Avatar answered Dec 23 '25 22:12

fhdrsdg


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 = []
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)
like image 43
Jainam Mehta Avatar answered Dec 23 '25 23:12

Jainam Mehta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!