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
Drawing a line between two mouse clicks using tkinter
Drawing lines between mouse clicks is a common GUI programming task. Tkinter provides event handling capabilities that allow us to capture mouse clicks and draw graphics on a canvas widget.
To draw a line between two points, we can follow these general steps ?
Create a canvas widget and pack it to display in the window.
Define a function draw_line() that works as the event handler when the user clicks.
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
Here's a complete example that creates a canvas and draws lines between pairs of mouse clicks ?
# 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")
win.title("Draw Line Between Mouse Clicks")
# Define a function to draw the line between two points
def draw_line(event):
global click_num
global x1, y1
if click_num == 0:
x1 = event.x
y1 = event.y
click_num = 1
print(f"First click at: ({x1}, {y1})")
else:
x2 = event.x
y2 = event.y
print(f"Second click at: ({x2}, {y2})")
# Draw the line in the given coordinates
canvas.create_line(x1, y1, x2, y2, fill="green", width=3)
click_num = 0 # Reset for next line
# 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)
# Initialize click counter
click_num = 0
# Add instructions
instructions = Label(win, text="Click twice on the canvas to draw a line between the points",
font=("Arial", 12))
instructions.grid(row=1, column=0, pady=10)
win.mainloop()
How It Works
The program uses several key components ?
Event Binding:
<Button-1>captures left mouse clicksGlobal Variables:
click_numtracks click count,x1, y1store first click coordinatesCanvas Methods:
create_line()draws lines with specified coordinates and stylingEvent Object:
event.xandevent.yprovide mouse click coordinates
Enhanced Version with Multiple Lines
Here's an improved version that allows drawing multiple lines and includes a clear button ?
from tkinter import *
class LineDrawer:
def __init__(self):
self.win = Tk()
self.win.geometry("700x400")
self.win.title("Interactive Line Drawing")
self.click_num = 0
self.x1 = 0
self.y1 = 0
self.setup_ui()
def setup_ui(self):
# Create canvas
self.canvas = Canvas(self.win, width=700, height=350,
background="white", relief=SUNKEN, bd=2)
self.canvas.grid(row=0, column=0, columnspan=2, padx=10, pady=10)
self.canvas.bind('<Button-1>', self.draw_line)
# Add control buttons
clear_btn = Button(self.win, text="Clear Canvas",
command=self.clear_canvas, bg="red", fg="white")
clear_btn.grid(row=1, column=0, padx=10, pady=5, sticky=W)
# Status label
self.status_label = Label(self.win, text="Click on canvas to start drawing",
font=("Arial", 10))
self.status_label.grid(row=1, column=1, padx=10, pady=5, sticky=E)
def draw_line(self, event):
if self.click_num == 0:
self.x1 = event.x
self.y1 = event.y
self.click_num = 1
self.status_label.config(text=f"First point: ({self.x1}, {self.y1}). Click again to draw line.")
else:
x2 = event.x
y2 = event.y
# Draw the line
self.canvas.create_line(self.x1, self.y1, x2, y2,
fill="blue", width=2, capstyle=ROUND)
self.click_num = 0
self.status_label.config(text=f"Line drawn to ({x2}, {y2}). Click to start new line.")
def clear_canvas(self):
self.canvas.delete("all")
self.click_num = 0
self.status_label.config(text="Canvas cleared. Click to start drawing.")
def run(self):
self.win.mainloop()
# Create and run the application
app = LineDrawer()
app.run()
Key Features
| Feature | Description | Code Component |
|---|---|---|
| Mouse Event Capture | Captures left mouse clicks | bind('<Button-1>', callback) |
| Coordinate Storage | Stores first click coordinates | Global variables x1, y1
|
| Line Drawing | Creates visual line between points | create_line(x1, y1, x2, y2) |
| State Management | Tracks click sequence |
click_num counter |
Conclusion
Drawing lines between mouse clicks in tkinter involves event binding, coordinate storage, and canvas drawing methods. Use <Button-1> to capture clicks and create_line() to draw between stored coordinates.
