Basics of Turtle programming in Python
In this tutorial, we will learn about the Basics of Turtle programming in Python.
turtle is a pre-installed Python library that helps programmers to create objects on a virtual canvas. There is a pen provided which is known as Turtle. Turtle programming is done on the IDLE environment provided by Python.
Basics of turtle Programming
Two important steps before we start with programming is to import the library and make a virtual canvas. We do this as follows:
import turtle canvas = turtle.getscreen() # Canvas page opens after this command.
After these two commands, you will see a separate window appears on the screen. Now let’s assign an object/name to the turtle.
myTurtle = turtle.Turtle()
>>> import turtle >>> canvas = turtle.getscreen() >>> myTurtle = turtle.Turtle() >>> myTurtle.fd(60) >>> myTurtle.lt(60) >>> myTurtle.fd(50)
Here, in this tutorial, we will learn how to customize your turtle.
Moving the Turtle
- Forward – .forward() / .fd()
- Backward – .backward() / .bk()
- Left – .left() / .lt()
- Right – .right() / .rt()
- To go from current position to any other point – .goto()
- Bring turtle back to its original location – .home()
myTurtle.fd(100) myTurtle.rt(90) myTurtle.bk(100) myTurtle.lt(90) myTurtle.fd(100)
Some inbuilt figures
- Circle – .circle(r) ;where r is the radius of circle
- Dot – .dot(r) ;where r is the radius of dot
Some other functionalities
Python provides some inbuilt functions so that you can customise your canvas. Use the following commands to change:
- the background colour of the canvas – .bgcolor(“color”)
- screen title – .title(“Your_title”)
- turtle size – .shapesize(length,width,outline_width)
- pen size – .pensize(size)
- pen color – .pencolor(“color”)
- Turtle shape – .shape(“shape”)
- speed of turtle – .speed(Speed)
Sometimes we need to fill in color inside our object/shape so we can use :
- .beginfill() – Tell the program that the image drawn is to be filled with color.
- .endfill() – This tells program that user has finished drawing and it should now be filled with color.
Sometimes, you might want to create discrete images . For this purpose you can the following commands:
- .penup() – To lift up your pen.
- .pendown() – To start drawing again.
Python turtle provides an undo option and clear screen option:
- Use .undo() and .clear() functions .
You can also refer: