Ask coding questions

← Back to all posts
Key pressed Python

Does anybody know how to detect key presses (eg. right arrow) and then move the turtle forward?

Geocube101 (623)

s.onkey(function, key) where s is the screen object, function is the function to execute and key is the key to test.
Right Arrow = 'right'
Left Arrow = 'left'
Up Arrow = 'up'
Down Arrow = 'down'
Note: Do not include the parenthesis in the onkey() function argument.
Correct = s.onkey(func, key)
Incorrect = s.onkey(func(), key)

RainbowBoy7324 (0)

@Geocube101 for me it says "Error: name 's' is not defined on line __". I tried doing "import s", but there's no module named s. Btw I am working on Python turtle.

Geocube101 (623)

s is a variable for the turtle Screen object

from turtle import Turtle, Screen #import turtle and turtle scren
s = Screen() #Declare screen
t = Turtle() # Declare new turtle
#Do stuff with screen

Turtle Screen documentation can be found here