turtle.ondrag() function in Python

The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.

turtle.ondrag()

This function is used to bind fun to mouse-move event on this turtle on canvas.

Syntax : turtle.ondrag(fun, btn, add)
Parameters :

  • fun : a function with two arguments, to which will be assigned the coordinates of the clicked point on the canvas
  • btn : number of the mouse-button defaults to 1 (left mouse button)
  • add : True or False. If True, new binding will be added, otherwise it will replace a former binding

Below is the implementation of the above method with an example :

Example  :



filter_none

edit
close

play_arrow

link
brightness_4
code

# importing package
import turtle
  
# method to call on drag
def fxn(x, y):
  
    # stop backtracking
    turtle.ondrag(None
  
    # move the turtle's angle and direction 
    # towards x and y
    turtle.setheading(turtle.towards(x, y))
  
    # go to x, y
    turtle.goto(x, y)
  
    # call again
    turtle.ondrag(fxn)
  
# set turtle speed
turtle.speed(10)
  
# make turtle screen object
sc = turtle.Screen()
  
# set screen size
sc.setup(400, 300)
  
# call fxn on drag
turtle.ondrag(fxn)
  
# take screen in mainloop
sc.mainloop()

chevron_right


Output :

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.