Monday, April 21, 2025

Python Turtle - Move Turtle with Arrow Keys

Moving turtle object using keyboard is easy. We need 4 dedicated functions. All of them will move in specific direction for 20 pixels or degrees. We will use original turtle functions fd(), bk(), left(), right() wrapped in our own functions:

def f():
    fd(20)

def b():
    bk(20)

def l():
    left(20)

def r():
    right(20)

Having custom functions is not enough, we need to tie them with keyboard arrows:

onkey(f, "Up")
onkey(b, "Down")
onkey(r, "Right")
onkey(l, "Left")

At the end we need to listen to those keypresses using listen() method:

listen()

 And this is full working script:

from turtle import *

t = Turtle()

def f():
    fd(20)

def b():
    bk(20)

def l():
    left(20)

def r():
    right(20)

onkey(f, "Up")
onkey(b, "Down")
onkey(r, "Right")
onkey(l, "Left")

listen()

 


This is another version where we can play around with colors, and our turtle object will automatically move when we keep arrows pressed.

We are substituting onkey() method with onkeypress() method. This is important to note.

from turtle import *

t = Turtle()
shapesize(10, 10, 10)

def f():
    color("red")
    fd(20)

def b():
    color("blue")
    bk(20)

def l():
    color("green")
    left(10)

def r():
    color("orange")
    right(10)

onkeypress(f, "Up")
onkeypress(b, "Down")
onkeypress(r, "Right")
onkeypress(l, "Left")

listen()


Definitely check YouTube tutorial on How to Move Turtle with Arrow Keys.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...