How to make the turtle follow the mouse in Python 3.6

感情迁移 提交于 2019-12-02 11:53:22

问题


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()

回答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.



来源:https://stackoverflow.com/questions/47598953/how-to-make-the-turtle-follow-the-mouse-in-python-3-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!