【问题标题】:How to make the turtle follow the mouse in Python 3.6如何在 Python 3.6 中让乌龟跟随鼠标
【发布时间】:2018-11-04 07:04:47
【问题描述】:
我被分配在 python 中创建一个类似版本的slither.io。我计划使用Turtle。如何让turtle 跟随我的鼠标而不必每次都单击?
这就是我点击时的方式,但我宁愿不必点击:
from turtle import *
turtle = Turtle()
screen = Screen()
screen.onscreenclick(turtle.goto)
turtle.getscreen()._root.mainloop()
【问题讨论】:
标签:
python
python-3.x
turtle-graphics
【解决方案1】:
它的关键是在海龟上使用ondrag() 事件处理程序。一个简短但不那么甜蜜的解决方案:
import turtle
turtle.ondrag(turtle.goto)
turtle.mainloop()
它可能会在您开始拖动后不久崩溃。一个更好的解决方案,使用更大的海龟进行拖动,并关闭拖动处理程序内的拖动处理程序以防止事件堆积:
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()
请注意,您必须单击并拖动海龟本身,而不仅仅是单击屏幕上的某个位置。如果您想让海龟跟随鼠标而不按住左键,请参阅my answer to Move python turtle with mouse pointer。