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 how I would do it when clicking, but I would rather not have to click:
from turtle import *
turtle = Turtle()
screen = Screen()
screen.onscreenclick(turtle.goto)
turtle.getscreen()._root.mainloop()
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.
来源:https://stackoverflow.com/questions/47598953/how-to-make-the-turtle-follow-the-mouse-in-python-3-6