Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Bind the Mouse button with the callback function to get full control over the function.
Example
Here's how to create a simple dot drawing application ?
# Import the required libraries
from tkinter import *
# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x350")
win.title("Draw Dots on Canvas")
# Define a function to draw the dot at click position
def draw_dot(event):
x = event.x
y = event.y
# Draw a small oval (dot) at the clicked coordinates
canvas.create_oval(x-5, y-5, x+5, y+5, fill="black", outline="black")
# Create a canvas widget
canvas = Canvas(win, width=700, height=350, background="white")
canvas.pack()
# Bind left mouse click to draw_dot function
canvas.bind('<Button-1>', draw_dot)
win.mainloop()
Output
Run the above code to display a window. When you click anywhere inside the canvas, it will draw a dot at that point.
Enhanced Example with Colored Dots
You can also create dots with different colors and sizes ?
from tkinter import *
import random
win = Tk()
win.geometry("700x350")
win.title("Colorful Dot Drawing")
colors = ["red", "blue", "green", "purple", "orange", "pink"]
def draw_colored_dot(event):
x = event.x
y = event.y
color = random.choice(colors)
size = random.randint(3, 8)
canvas.create_oval(x-size, y-size, x+size, y+size,
fill=color, outline=color)
canvas = Canvas(win, width=700, height=350, background="white")
canvas.pack()
canvas.bind('<Button-1>', draw_colored_dot)
win.mainloop()
Key Points
event.xandevent.ygive the mouse click coordinatescreate_oval()method draws circular shapes when width equals height<Button-1>represents left mouse button click eventThe dot size is controlled by adjusting the oval's bounding rectangle
Conclusion
Drawing dots on canvas click events in Tkinter is straightforward using bind() method and create_oval(). You can enhance the functionality by adding colors, different sizes, or even connecting dots with lines.
