Skip to content Skip to sidebar Skip to footer

How To Make The Turtle Follow The Mouse In Python 3.6

I'm assigned to create a similar version of slither.io in python. I planned on using Turtle. How do I make the turtle follow my mouse without having to click every time? This is h

Solution 1:

The key to it is to use the ondrag() event handler on a turtle. A short and not so sweet solution:

import turtle
turtle.ondrag(turtle.goto)
turtle.mainloop()

which will likely crash shortly after you start dragging. A better solution with a larger turtle to drag, and that turns off the drag handler inside the drag hander to prevent events from piling up:

from turtle import Turtle, Screen

def dragging(x, y):
    yertle.ondrag(None)
    yertle.setheading(yertle.towards(x, y))
    yertle.goto(x, y)
    yertle.ondrag(dragging)

screen = Screen()

yertle = Turtle('turtle')
yertle.speed('fastest')

yertle.ondrag(dragging)

screen.mainloop()

Note that you have to click and drag the turtle itself, not just click somewhere on the screen. If you want to get the turtle to follow the mouse without keeping the left button held down, see my answer to Move python turtle with mouse pointer.

Post a Comment for "How To Make The Turtle Follow The Mouse In Python 3.6"