Python – How to make turtle follow the mouse in Python 3.6

How to make turtle follow the mouse in Python 3.6… here is a solution to the problem.

How to make turtle follow the mouse in Python 3.6

I was assigned to create a similar version of slither.io in python. I plan to use Turtle. How do I get turtle to follow my mouse without having to click every time?
That’s what I do when I click, but I’d rather not have to click :

from turtle import *
turtle = Turtle()
screen = Screen()
screen.onscreenclick(turtle.goto)
turtle.getscreen()._root.mainloop()

Solution

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

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

It may crash shortly after you start dragging. A better solution is to drag the larger turtle and turn off the drag handler inside the drag handler 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 the turtle to follow the mouse without holding down the left button, see my answer to Move python turtle with mouse pointer .

Related Problems and Solutions