python - 如何使用Python通过空格键开始移动 turtle

标签 python turtle-graphics

我正在尝试在 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/

相关文章:

python - 在 Python 中使用随机 x、y 坐标绘制阿基米德螺线

python - 带 turtle 图形的 14 段显示

python - python 中的 turtle 迷宫。我不知道如何避免 turtle 穿墙和作弊

python - 绘制一年时间序列中的每周滴答数据

python - 在终端中设置路径

python - 无法使用给定 session 评估张量 : the tensor's graph is different from the session's graph

python - 如何在类中导入 Turtle 模块?

python - 各种 TensorFlow 数据加载习惯适用于哪些场景?

python - 使用乘法 ( * ) 意外行为生成子列表

python - 在 Python 中嵌套 for 循环来制作三角形图案