non continuous line user draw tkinter python non continuous line user draw tkinter python tkinter tkinter

non continuous line user draw tkinter python


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, Tkline = []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()


import tkinter as tkfrom time import sleepdef getpoint1(event):    global x, y    x, y = event.x, event.ydef getpoint2(event):    global x1, y1    x1, y1 = event.x, event.ydef 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.