Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Example
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the window
win.geometry("700x350")
# Define a function to draw the line between two points
def draw_line(event):
x1=event.x
y1=event.y
x2=event.x
y2=event.y
# 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)
click_num=0
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.
