如何使用python通过空格键开始移动乌龟 [英] How to start moving a turtle via space bar with python

查看:44
本文介绍了如何使用python通过空格键开始移动乌龟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 中设置一个简单的海龟程序,我可以通过按下空格键开始移动海龟,他一直移动直到我再次按下空格键.我可以让他用空格键移动一个固定的距离,但不能让它继续.

I'm trying to set up a simple turtle program in python where I can start moving the turtle with a press of the space bar, and he keeps moving until I hit the space bar again. I can get him to move a fixed distance with the space press but can't get it to continue.

这是我正在使用的:

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

推荐答案

我没有看到你的问题得到了答案:

I don't see that you ever got an answer to your query:

按下空格键开始移动乌龟,他一直保持移动直到我再次按下空格键

start moving the turtle with a press of the space bar, and he keeps moving until I hit the space bar again

建议的 onkeypress() 修复不会这样做.这是一个简单的例子,可以做你想做的事情,当你点击空格键时启动乌龟,再次点击空格键时停止它:

The suggested onkeypress() fix doesn't do this. Here's a simplified example that does what you want, starts the turtle when you hit the space bar and stops it when you hit the space bar again:

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

我在这个例子中使用了圆周运动,所以你可以随意启动和停止海龟.

I've used circular motion in this example so you can start and stop the turtle as much as you want.

这篇关于如何使用python通过空格键开始移动乌龟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆