中让海龟跟随鼠标

中让海龟跟随鼠标

本文介绍了如何在 Python 3.6 中让海龟跟随鼠标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被分配在 python 中创建一个类似版本的 slither.io.我计划使用 Turtle.如何让 turtle 跟随我的鼠标而不必每次都点击?这是我点击时的做法,但我宁愿不必点击:

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

推荐答案

它的关键是在海龟上使用 ondrag() 事件处理程序.一个简短而不那么甜蜜的解决方案:

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

请注意,您必须单击并拖动海龟本身,而不仅仅是单击屏幕上的某处.如果你想让乌龟在不按住左键的情况下跟随鼠标,请参阅 我对 Move python turtle with鼠标指针.

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.

这篇关于如何在 Python 3.6 中让海龟跟随鼠标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:46