Reputation: 31
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()
Upvotes: 2
Views: 3839
Reputation: 41
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)
Upvotes: 3
Reputation: 10532
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()
Upvotes: 4
Reputation:
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.y
def release(l):
store['x2'] = l.x
store['y2'] = l.y
draw() # Release the mouse and draw
def draw():
canvas.create_line(store['x'],store['y'],store['x2'],store['y2'])
canvas.bind('<ButtonPress-1>', click)
canvas.bind('<ButtonRelease-1>', release)
mainloop()
Upvotes: 1