How to draw a line following mouse coordinates with tkinter?


To draw a line following mouse coordinates, we need to create a function to capture the coordinates of each mouse-click and then draw a line between two consecutive points. Let's take an example and see how it can be done.

Steps −

  • Import the tkinter library and create an instance of tkinter frame.

  • Set the size of the frame using geometry method.

  • Create a user-defined method "draw_line" to capture the x and y coordinates of each mouse click. Then, use the create_line() method of Canvas to draw a line between two consecutive points.

  • Bind the left-click of the mouse with the draw_line method.

  • Finally, run the mainloop of the application window.

Example

# Import the library
import tkinter as tk

# Create an instance of tkinter
win = tk.Tk()

# Window size
win.geometry("700x300")

# Method to draw line between two consecutive points
def draw_line(e):
   x, y = e.x, e.y
   if canvas.old_coords:
      x1, y1 = canvas.old_coords
      canvas.create_line(x, y, x1, y1, width=5)
   canvas.old_coords = x, y

canvas = tk.Canvas(win, width=700, height=300)
canvas.pack()
canvas.old_coords = None

# Bind the left button the mouse.
win.bind('<ButtonPress-1>', draw_line)

win.mainloop()

Output

It will track the left-clicks of the mouse and draw a line between each two consecutive points.

Updated on: 26-Oct-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements