我正在尝试在 python 中设置一个简单的 turtle 程序,在其中我可以通过按空格键开始移动 turtle ,并且他会一直移动,直到我再次按下空格键。我可以用空格键让他移动固定距离,但无法让它继续。
这是我正在处理的内容:
from turtle import *
# PUT YOUR CODE HERE
setup(800,600)
home()
pen_size = 2
color("blue")
title("Turtle")
speed("fastest")
drawdist= 25
current_state = penup
next_state = pendown
#Button Instructions
def move_up():
seth(90)
forward(drawdist)
def move_down():
seth(270)
forward(drawdist)
def move_left():
seth(180)
forward(drawdist)
def move_right():
seth(0)
forward(drawdist)
def space_bar():
seth(90)
forward(drawdist)
global current_state, next_state
next_state()
current_state, next_state = next_state, current_state
#Change Pen Color
def red():
color("red")
def green():
color("green")
def blue():
color("blue")
#Button Triggers
s= getscreen()
s.onkey(move_up,"Up")
s.onkey(move_down,"Down")
s.onkey(move_left,"Left")
s.onkey(move_right,"Right")
s.onkey(space_bar,"space")
s.onkey(red,"r")
s.onkey(green,"g")
s.onkey(blue,"b")
listen()
done()
最佳答案
我没有看到您的查询得到答案:
start moving the turtle with a press of the space bar, and he keeps moving until I hit the space bar again
建议的 onkeypress()
修复不会执行此操作。这是一个简化的示例,它可以执行您想要的操作,当您按下空格键时启动 turtle ,并在您再次按下空格键时停止它:
from turtle import Turtle, Screen
screen = Screen()
turtle = Turtle(shape="turtle")
turtle.speed("fastest")
def current_state():
global moving
moving = False
turtle.penup()
def next_state():
global moving
turtle.pendown()
moving = True
move()
def space_bar():
global current_state, next_state
next_state()
current_state, next_state = next_state, current_state
def move():
if moving:
turtle.circle(100, 3)
screen.ontimer(move, 50)
current_state()
screen.onkey(space_bar, "space")
screen.listen()
screen.mainloop()
我在本例中使用了圆周运动,因此您可以根据需要启动和停止 turtle 。
关于python - 如何使用Python通过空格键开始移动 turtle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29904032/