How to draw a line following mouse coordinates with tkinter?
Tkinter is a module in Python that is used for creating user interfaces. It provides several widgets to build graphical user interfaces and a canvas widget to draw different objects like lines, circles, rectangles, etc. In this article, we’ll learn to create a line that follows the mouse coordinates in Tkinter.
Creating a Canvas Widget
Firstly, we need to import the tkinter
module and create the main window using the Tk()
function. Then, we can create a canvas widget using the Canvas()
function and pack it onto the window using the pack()
method.
import tkinter as tk
win = tk.Tk()
canvas = tk.Canvas(win, width=500, height=500)
canvas.pack()
Here, we created an instance of Tk()
, and created a canvas widget with a width and height of 500 each. We then packed the canvas onto the window.
Binding the Mouse Motion
Now, we need to bind the motion of the mouse to a callback function that updates the position of the line on the canvas. To do that, we use the bind()
method on the canvas widget. The bind()
method takes two arguments – the event to bind (in this case, <Motion>
, which represents mouse movement), and the function to be called when the event is triggered.
def draw(event):
x, y = event.x, event.y
canvas.delete("line") # delete previous line
canvas.create_line(0, 0, x, y, tags="line") # create new line
canvas.bind("<Motion>", draw)
Here, we created a draw()
function that takes an event object. The event
object has the current position of the mouse – we use that to update the position of the line on the canvas. The canvas.delete()
method removes the previously created line (identified by the tag line
) from the canvas. The canvas.create_line()
method creates a new line between the point (0, 0) and the current mouse coordinates. We use the tags
argument to give the line a unique identifier so we can delete it later.
Finally, we bound the <Motion>
event to the draw()
function using the bind()
method.
Putting it all together
Let’s put everything together and see how it looks like.
import tkinter as tk
def draw(event):
x, y = event.x, event.y
canvas.delete("line") # delete previous line
canvas.create_line(0, 0, x, y, tags="line") # create new line
win = tk.Tk()
canvas = tk.Canvas(win, width=500, height=500)
canvas.pack()
canvas.bind("<Motion>", draw)
win.mainloop()
When you run the above code, you should see a window with a line following your mouse cursor.
Conclusion
In this article, we learned how to draw a line following the mouse coordinates in Tkinter. We used the Canvas
widget to draw the line, and the bind()
method to capture the mouse movement and update the position of the line. Tkinter provides several other functions for drawing shapes, and you can explore them to create more complex designs.