turtle.ondrag() function in Python

The turtle.ondrag() function binds a function to a mouse-move event on the turtle while a button is held down. This lets you drag the turtle around the screen.

Syntax: turtle.ondrag(fun, btn=1, add=None)
Parameters: fun – a function with two arguments (x, y coordinates); btn – mouse button number.

Let us see an example to implement the turtle.ondrag() function in Python:

Demo36.py

# turtle.ondrag() function in Python
# Code by Studyopedia

import turtle

window = turtle.Screen()
t = turtle.Turtle()

def drag_handler(x, y):
    t.ondrag(None)  # Disable drag during processing
    t.goto(x, y)
    t.ondrag(drag_handler)  # Re-enable drag

t.ondrag(drag_handler)  # Bind drag event

window.mainloop()

The following is the output:

turtle.ondrag() function in Python

In the above code, we followed the below steps:

  • Import module: import turtle loads the turtle graphics library.
  • Create screen: window = turtle.Screen() opens the drawing window.
  • Create turtle: t = turtle.Turtle() creates the turtle you’ll control.
  • Define drag handler: def drag_handler(x, y): processes drag events.
    • Temporarily disable drag: t.ondrag(None) prevents recursive re-entry while moving the turtle.
    • Move turtle: t.goto(x, y) moves to the current mouse position (draws if the pen is down).
    • Re-enable drag: t.ondrag(drag_handler) restores the handler so dragging continues smoothly.
  • Bind drag event: t.ondrag(drag_handler) triggers the handler while you drag the turtle with the mouse held down.
  • Run event loop: window.mainloop() keeps the window open and responsive to drag events.

If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

turtle.ontimer() function in Python
turtle.exitonclick() function in Python
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment