Reputation: 313
So here's the code for a program where the user can click on a point and it draws a point and then subsequent clicks draw more lines all attached to the previous line. How would I edit this program to just let the user press down on the button and have like (xp1, yp1) and then drag some where and release at (xp2, yp2) then draw a line between (xp1, yp1) and (xp2, yp2). Finally it would let the user create many different lines then eventually be able to clear the canvas screen by pressing "c". Like I know the last thing would have to bind some function to "c" but I don't know what it is.
from Tkinter import Canvas, Tk, mainloop
import Tkinter as tk
# Image dimensions
w,h = 640,480
# Create canvas
root = Tk()
canvas = Canvas(root, width = w, height = h, bg = 'white')
canvas.pack()
# Create poly line
class PolyLine(object):
def __init__(x, canvas):
x.canvas = canvas
x.start_coords = None # first click
x.end_coords = None # subsequent clicks
def __call__(x, event):
coords = event.x, event.y # coordinates of the click
if not x.start_coords:
x.start_coords = coords
return
x.end_coords = coords # last click
x.canvas.create_line(x.start_coords[0], # first dot x
x.start_coords[1], # first dot y
x.end_coords[0], # next location x
x.end_coords[1]) # next location y
x.start_coords = x.end_coords
canvas.bind("<Button-1>", PolyLine(canvas)) # left click is used
mainloop()
Thank you so much for your time! I really appreciate it!
Upvotes: 1
Views: 931
Reputation: 409
import tkinter as tk
from time import sleep
def getpoint1(event):
global x, y
x, y = event.x, event.y
def getpoint2(event):
global x1, y1
x1, y1 = event.x, event.y
def drawline(event):
canvas.create_line(x, y, x1, y1)
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
root.bind('q', getpoint1)
root.bind('w', getpoint2)
root.bind('<Button-1>', drawline)
root.mainloop()
This is pretty much what you asked for on your comment, but with different keys.
Upvotes: 1
Reputation: 16179
For the drawing line part, I use a global list variable to store the line points. If the list is empty, then I store the line starting point coordinates inside the list. Otherwise, I draw the line between the starting point and the current cursor position and I reset the list.
For the clearing part, what you need is to bind the canvas.delete
method to "c" key press.
from Tkinter import Canvas, Tk
line = []
def on_click(event):
global line
if len(line) == 2:
# starting point has been defined
line.extend([event.x, event.y])
canvas.create_line(*line)
line = [] # reset variable
else:
# define line starting point
line = [event.x, event.y]
def clear_canvas(event):
canvas.delete('all')
root = Tk()
canvas = Canvas(root, bg='white')
canvas.pack()
canvas.bind("<Button-1>", on_click)
root.bind("<Key-c>", clear_canvas)
root.mainloop()
Upvotes: 2