How to draw a dot on a canvas on a click event in Tkinter Python?


Consider a case for creating a GUI application such that when we click on the window with a mouse button, it stores the coordinates and draws a dot. Tkinter provides events that allow the user to bind the keys or buttons with the functions.

To draw a dot on click event, we can follow these general steps −

  • Create a canvas widget and pack it to display in the window.

  • Define a function draw_dot() that works as the event when the user does the click event.

  • Create a global variable that counts the number of clicks in the canvas.

  • If the count becomes two, then draw a line between the first and second coordinates.

  • Bind the Mouse button with the callback function to get full control over the function.


# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window

# Set the size of the window

# Define a function to draw the line between two points
def draw_line(event):
   # Draw an oval in the given co-ordinates
   canvas.create_oval(x1,y1,x2,y2,fill="black", width=20)

# Create a canvas widget
canvas=Canvas(win, width=700, height=350, background="white")
canvas.grid(row=0, column=0)
canvas.bind('<Button-1>', draw_line)



Run the above code to display a window. When you click anywhere inside the canvas, it will draw a dot at that point.

Updated on 05-Aug-2021 14:02:52