我正在编写一个程序,通过按下箭头键将 turtle 向不同方向移动。我希望能够通过按住相应的箭头键而不是重复按下它来将其移动到特定方向。然而,当我按住箭头键几秒钟后松开箭头键时, turtle 会向后移动一点,而不是立即停止。它向后移动的量取决于我按住按键移动它的时间。
你能帮我解决这个问题或者建议用 turtle 模块实现这个问题的另一种方法吗?
注意:我观察到,当我按住该键时,直到松开该键时才会绘制线条。我不确定它是否符合预期或与此问题相关。
注释 2:我使用 onkeypress 方法来处理“按住键”事件。我尝试使用 onkeyrelease(None, arrow_key) 方法来解决这个问题,但它也不起作用。
这是我的代码:
from turtle import Turtle, Screen
def move_right():
turtle.setheading(0)
turtle.forward(25)
def move_up():
turtle.setheading(90)
turtle.forward(25)
def move_left():
turtle.setheading(180)
turtle.forward(25)
def move_down():
turtle.setheading(270)
turtle.forward(25)
turtle = Turtle()
screen = Screen()
screen.onkeypress(move_right, "Right")
screen.onkeypress(move_up, "Up")
screen.onkeypress(move_left, "Left")
screen.onkeypress(move_down, "Down")
screen.listen()
screen.exitonclick()
最佳答案
花了一分钟才弄清楚。不知道为什么turtle.forward()
会在释放后恢复到之前的位置。 Python 的 Turtle 模块有缺陷。它应该留在你放置的地方,但无论出于何种原因,它又冒出来了。
这将达到您的预期。
#! /usr/bin/python3
from turtle import Turtle, Screen
turtle = Turtle()
screen = Screen()
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def right():
turtle.setx( turtle.pos()[0] +25 )
def up():
turtle.sety( turtle.pos()[1] +25 )
def left():
turtle.setx( turtle.pos()[0] -25 )
def down():
turtle.sety( turtle.pos()[1] -25 )
screen.onkeypress( right, "Right")
screen.onkeypress( up, "Up")
screen.onkeypress( left, "Left")
screen.onkeypress( down, "Down")
screen.listen()
screen.exitonclick()
## eof ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
编辑:哦,是重复 setheading()
函数导致挂起。
首先测试 turtle 的航向,然后仅在需要时设置它。
#! /usr/bin/python3
from turtle import Turtle, Screen
turtle = Turtle()
screen = Screen()
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def right():
if turtle.heading() != 0: turtle.setheading(0)
turtle.forward(25)
def up():
if turtle.heading() != 90: turtle.setheading(90)
turtle.forward(25)
def left():
if turtle.heading() != 180: turtle.setheading(180)
turtle.forward(25)
def down():
if turtle.heading() != 270: turtle.setheading(270)
turtle.forward(25)
screen.onkeypress( right, "Right")
screen.onkeypress( up, "Up")
screen.onkeypress( left, "Left")
screen.onkeypress( down, "Down")
screen.listen()
screen.exitonclick()
## eof ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
关于Python-Turtle - 通过按住某个键来移动 turtle : releasing the key moves the turtle back instead of stopping it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67580515/