Tkinter Canvas Mouse dragging to draw lines
Python’s tkinter module does not provide a tool for drawing points in the Canvas control section, but we can use the mouse dragging with the paint event handler bound to it, in which we can get the mouse coordinates and then use the create_oval( ) method to draw the miniaturized circle in such a way that the coordinates of the upper left corner of the circle are the same as the left scale of the lower right corner, see the following example.
Example#1
Design a simple drawing program, this program can draw lines if you drag the mouse while executing.
from tkinter import *
def paint(event): # Drag and drop for drawing
x1,y1 = (event.x,event.y) # Set the upper left corner coordinates
x2,y2 = (event.x,event.y) # Set lower right corner coordinates
x1,y1 = (event.x-1,event.y-1) # Set the upper left corner coordinates
x2,y2 = (event.x+1,event.y+1) # Set lower right corner coordinates
canvas.create_oval(x1,y1,x2,y2,fill="blue")
def cls(): # Clear screen
canvas.delete("all")
tk = Tk()
tk.title("apidemos.com")
lab = Label(tk,text='Drag and drop the mouse to draw') # Create title
lab.pack()
canvas = Canvas(tk,width=640, height=300) # Create Canvas
canvas.pack()
btn = Button(tk,text="Clear",command=cls) # Create Clear Button
btn.pack(pady=5)
canvas.bind("<B1-Motion>",paint) # Mouse drag and drop binding paint
tk.mainloop()
Output:
Line 12 of the above program uses the delete() method, which, with "all" inside the method, deletes all the drawings, which is equivalent to clearing the canvas for this program. If you want to make the drawn lines thicker, you can subtract 1 from the (x,y) coordinates in the upper left corner and add 1 to the (x,y) coordinates in the lower right corner.