如何用python开始通过空格键移动乌龟

时间:2015-04-27 19:10:50

标签: python turtle-graphics

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

以下是我正在使用的内容:

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

3 个答案:

答案 0 :(得分:1)

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

  

按下空格键开始移动乌龟,他继续   移动直到我再次击中空格键

建议的onkeypress()修正无法解决此问题。这是一个简单的例子,可以做你想要的,当你点击空格键时启动乌龟,当你再次点击空格键时停止它:

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

我在这个例子中使用过圆周运动,所以你可以随心所欲地开始和停止乌龟。

答案 1 :(得分:0)

用'onkeypress'功能替换'onkey'功能。

'onkey'功能无论按住键都会触发一次,而'onkeypress'会按下按键时发出的声音。

答案 2 :(得分:0)

正确和最简单的方法是这样(不适用于活动主持人空格键,这仅是事件监听器):

import turtle 
import random

t = turtle.Turtle()
screen = turtle.Screen(

def goForward():
  t.forward(input_value)

screen.onkey(goForward, "Forward")

主题标签中的单词“ right”仅表示按右键。