Skip to content Skip to sidebar Skip to footer

Python Turtle Graphics Keyboard Commands

Anybody have any insight into controlling turtle graphics in python 2.7 with keyboard commands? I have done extensive research on this website and others and feel like I am doing t

Solution 1:

When you specified import * you don't have to use turtle., also you have to use mainloop() read (infinite loop) to watch over user interactions, in your example wn is also unnecessary.

Here is the working code...

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

defk1():
    move.forward(45)

defk2():
    move.left(45)

defk3():
    move.right(45)

defk4():
    move.back(45)

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

listen()
mainloop()

Solution 2:

import turtle

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

Lewi = turtle.Turtle()

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

Lewi.penup()



defup():
    Lewi.sety(Lewi.ycor()+10)

defdown():
    Lewi.sety(Lewi.ycor()-10)

defleft():
    Lewi.forward(-10)

defright():
    Lewi.forward(10)





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

turtle.mainloop()

I just recently came up with this. Hope it helps!

Solution 3:

I found that with the code above and my example code, the keypresses were not registered until I clicked on the window. In my example, the turtle would move but the left/right action would not occur until I clicked on the window.

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)

Solution 4:

When you issue commands like this:

move = turtle.Turtle()
showturtle()

you're actually talking to two different turtles, your turtle object in 'move' and the default turtle. Most of the screen and default turtle methods can be called without an explicit object as they are also top level functions. To avoid confusion, I recommend you always import turtle this way:

from turtle importTurtle, Screen

and explicitly create your own turtle(s) and screen object. This way you won't be able to call the alternative functiions and won't get confused. Your example rewritten with the above in mind:

from turtle import Turtle, Screen

screen = Screen()

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

move = Turtle(shape="turtle")

defk1():
    move.forward(10)

defk2():
    move.left(45)

defk3():
    move.right(45)

defk4():
    move.backward(10)

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

screen.listen()

screen.exitonclick()

Post a Comment for "Python Turtle Graphics Keyboard Commands"