Open In App

Python Turtle – Graphics Keyboard Commands

Python Turtle module is a graphical tool that can be used to draw simple graphics on the screen using a cursor. Python Turtle was a part of Logo programming language which had similar purpose of letting the users draw graphics on the screen with the help of simple commands. Turtle is a pre-installed module and has inbuilt commands and features that can be used to draw pictures on the screen. This article will be primarily focused on creating a graphic using keyboard commands along with how the same methodology can be used to add or change color to the graphic.

Functions Used:

Given below are two approaches that deal and discuss how to create a graphics keyboard



Method 1

Approach

Program






import turtle
from turtle import *
 
setup(500, 500)
Screen()
turtle = turtle.Turtle()
turtle.speed(0)
showturtle()
 
 
def up():
    turtle.setheading(90)
    turtle.forward(100)
 
 
def down():
    turtle.setheading(270)
    turtle.forward(100)
 
 
def left():
    turtle.setheading(180)
    turtle.forward(100)
 
 
def right():
    turtle.setheading(0)
    turtle.forward(100)
 
 
listen()
onkey(up, 'Up')
onkey(down, 'Down')
onkey(left, 'Left')
onkey(right, 'Right')
 
mainloop()

Output

Method 2: changing color

This is similar to the previous example with the addition of few more keys. Now we have added keys to change the color of the line. 

Also, the thickness of the line is increased by setting the width o the turtle to 5px using the width() method.

Program




import turtle
from turtle import *
 
setup(500, 500)
Screen()
turtle = turtle.Turtle()
turtle.speed(0)
turtle.width(5)
showturtle()
 
 
def up():
    turtle.setheading(90)
    turtle.forward(100)
 
 
def down():
    turtle.setheading(270)
    turtle.forward(100)
 
 
def left():
    turtle.setheading(180)
    turtle.forward(100)
 
 
def right():
    turtle.setheading(0)
    turtle.forward(100)
 
 
def r():
    turtle.color("red")
 
 
def g():
    turtle.color("green")
 
 
def b():
    turtle.color("blue")
 
 
def z():
    turtle.color("black")
 
 
listen()
onkey(up, 'Up')
onkey(down, 'Down')
onkey(left, 'Left')
onkey(right, 'Right')
onkey(z, "z")
onkey(r, 'r')
onkey(g, 'g')
onkey(b, 'b')
 
mainloop()

Output


Article Tags :