Python Turtle图形键盘命令

时间:2013-04-13 07:13:55

标签: python-2.7 keyboard-events turtle-graphics

任何人都有使用键盘命令控制python 2.7中的龟图形的任何见解?我已经在这个网站和其他网站上进行了广泛的研究,感觉我做的是正确的,但它只是不想为我工作。以下是我到目前为止,谁能告诉我哪里出错????

from turtle import *
turtle.setup(500, 500)
wn = turtle.Screen()
wn.title("Turtle Keys")
move = turtle.Turtle()
showturtle()

def k1():
move.forward(45)

def k2():
move.left(45)

def k3():
move.right(45)

def k4():
move.back(45)

wn.onkey(k1, "Up")
wn.onkey(k2, "Left")
wn.onkey(k3, "Right")
wn.onkey(k4, "Down")

wn.listen()

4 个答案:

答案 0 :(得分:5)

当您指定import *时,您不必使用turtle。,您还必须使用mainloop()read(无限循环)来监视用户交互,在您的示例中,wn也是不必要的。

这是工作代码......

from turtle import *
setup(500, 500)
Screen()
title("Turtle Keys")
move = Turtle()
showturtle()

def k1():
    move.forward(45)

def k2():
    move.left(45)

def k3():
    move.right(45)

def k4():
    move.back(45)

onkey(k1, "Up")
onkey(k2, "Left")
onkey(k3, "Right")
onkey(k4, "Down")

listen()
mainloop()

答案 1 :(得分:1)

import turtle

image = "C:/Python27/PythonProgramming/picture.gif"
screenr = turtle.Screen()

Lewi = turtle.Turtle()

screenr.addshape(image)
Lewi.shape(image)

Lewi.penup()



def up():
    Lewi.sety(Lewi.ycor()+10)

def down():
    Lewi.sety(Lewi.ycor()-10)

def left():
    Lewi.forward(-10)

def right():
    Lewi.forward(10)





screenr.onkey(up, "Up")
screenr.onkey(down, "Down")
screenr.onkey(right, "Right")
screenr.onkey(left, "Left")
screenr.listen()

turtle.mainloop()

我最近想出了这个。希望它有所帮助!

答案 2 :(得分:0)

我发现使用上面的代码和我的示例代码,直到我点击窗口才能注册按键。在我的例子中,乌龟会移动但是在我点击窗口之前不会发生左/右动作。

import turtle

def rightTurn():
   bob.rt(90)

def leftTurn():
   bob.lt(90)


wn=turtle.Screen()
wn.bgcolor('lightblue')

bob=turtle.Turtle()

wn.onkeypress(rightTurn, "Right")
wn.onkeypress(leftTurn, "Left")
wn.listen()


while True:
   bob.fd(1)

答案 3 :(得分:0)

当您发出如下命令时:

move = turtle.Turtle()
showturtle()

你实际上正在与两只不同的海龟交谈,你的乌龟对象在'move'和默认的乌龟。大多数屏幕和默认龟方法都可以在没有显式对象的情况下调用,因为它们也是顶级函数。为避免混淆,我建议你总是这样导入龟:

from turtle import Turtle, Screen

并显式创建自己的乌龟和屏幕对象。这样你就无法调用替代函数,也不会混淆。你的例子用以上内容重写:

from turtle import Turtle, Screen

screen = Screen()

screen.setup(500, 500)
screen.title("Turtle Keys")

move = Turtle(shape="turtle")

def k1():
    move.forward(10)

def k2():
    move.left(45)

def k3():
    move.right(45)

def k4():
    move.backward(10)

screen.onkey(k1, "Up")
screen.onkey(k2, "Left")
screen.onkey(k3, "Right")
screen.onkey(k4, "Down")

screen.listen()

screen.exitonclick()