简体   繁体   中英

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

@jasonharper is correct about the capitalization issue (+1) but you clearly have other issues with this code as you import turtle two different ways. Ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM