turtle.onkey() function in Python

The turtle.onkey() function binds a function to a key-press event. The turtle screen must be listening for events (listen()) for this to work.

Syntax: turtle.onkey(fun, key)
Parameters: fun – a function with no arguments; key – a string representing the key (e.g., “a”, “space”, “Up”).

Let us see an example to implement the turtle.onkey() function in Python:

Demo32.py

# turtle.onkey() function in Python
# Code by Studyopedia

import turtle

window = turtle.Screen()
t = turtle.Turtle()

def move_forward():
    t.forward(50)

def move_backward():
    t.backward(50)

window.onkey(move_forward, "Up")     # Bind up arrow key
window.onkey(move_backward, "Down")  # Bind down arrow key
window.listen()                      # Start listening for events

window.mainloop()

The following is the output:

turtle.onkey() function in Python

In the above code, we followed the below steps:

  1. Import the module: import turtle loads Python’s turtle graphics library.
  2. Create the screen: window = turtle.Screen() opens the drawing window.
  3. Create the turtle: t = turtle.Turtle() creates the turtle you’ll control.
  4. Define forward action: def move_forward(): t.forward(50) moves the turtle forward 50 units when called.
  5. Define backward action: def move_backward(): t.backward(50) moves the turtle backward 50 units when called.
  6. Bind Up key: window.onkey(move_forward, “Up”) triggers move_forward() when the Up arrow is pressed.
  7. Bind Down key: window.onkey(move_backward, “Down”) triggers move_backward() when the Down arrow is pressed.
  8. Enable key listening: window.listen() starts listening for keyboard events; without this, key presses won’t be captured.
  9. Run event loop: window.mainloop() keeps the window open and responsive to key presses until it’s closed.

If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

turtle.onclick() function in Python
turtle.onscreenclick() function in Python
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment