Search code examples
pythonturtle-graphicspython-turtle

Detecting Keypresses in the Turtle module in Python


I want it so my Up key moves the turtle and my S key cleans the screen. Also, the up key command works:

import turtle
from turtle import Turtle, Screen

screen = Screen()

jack = Turtle("turtle")
jack.color("red", "green")
jack.pensize(10)
jack.speed(0)

def clean(x,y):
    jack.clear()
def move():
    jack.forward(100)

turtle.listen()
turtle.onkey(clean,"S")
turtle.onkey(move,"Up")

screen.mainloop()

Solution

  • @jasonharper is correct about the capitalization issue (+1) but you clearly have other issues with this code as you import turtle two different ways. I.e. you're mixing turtle's object-oriented API with its functional API. Let's rewrite the code to just use the object-oriented API:

    from turtle import Screen, Turtle
    
    def move():
        turtle.forward(100)
    
    screen = Screen()
    
    turtle = Turtle('turtle')
    turtle.color('red', 'green')
    turtle.pensize(10)
    turtle.speed('fastest')
    
    screen.onkey(turtle.clear, 's')
    screen.onkey(move, 'Up')
    screen.listen()
    
    screen.mainloop()
    

    I've changed variable names to make it clear which methods are screen instance methods and which are turtle instance methods. Your double import obscured this.