turtle
is Python’s pre-installed library that enables users to create small games, animations, etc., with easy-to-understand codes.
With minimal and easy-to-understand codes that create beautiful shapes, it is a great way for kids to start their coding journey
turtle
turtle
is a pre-installed library in Python; therefore, we don’t need to install it explicitly.
The turtle
module and its methods can be used in a program once it is imported into your Python environment, which can be done as follows:
import turtle
Since turtle
will perform graphic actions, it requires a canvas or separate workspace area to act on our commands. The turtle
canvas or screen can be initialized, as shown below:
scr = turtle.getscreen()
We need a turtle
to perform actions on the canvas. turtle
object is instantiated by the creation of an object of the Turtle
class defined in the turtle
module.
The turtle object is created as follows:
flippy = turtle.Turtle()
Now, the turtle
named flippy
is ready to receive commands to perform graphical actions on the canvas or screen.
To provide commands to the turtle, we use the turtle
's pre-defined methods.
Example:
import turtle# Asking user for the length of the Square sides.s=int(input("Enter the side of a Square\n>>> "))# Creating a Canvas or Screen:scr = turtle.getscreen()# Creating turtle object to perform actions.flippy = turtle.Turtle()# A loop which repeats 4 times to draw a sqaure:for i in range(4):# flippy is the name of our turtle.# fd() or forward() method is used to move turtle forward and draw a line while it moves.flippy.fd(s)# lt() or left() method is used to turn turtle anti-clockwise by a desired angle given as parameter.flippy.lt(90)
Methods | Description |
filling() | It returns fill state of the turtle-True if filling, False otherwise. |
begin_fill() | This method is called before drawing a shape which needs to filled with color. |
end_fill() | This method fills the shape drawn after the last call to begin_fill() |
import turtles=int(input("Enter the side of a Square\n>>> "))scr = turtle.getscreen()flippy = turtle.Turtle()flippy.begin_fill()print(flippy.filling()) # Prints Truefor i in range(4):flippy.fd(s)flippy.lt(90)flippy.end_fill()print(flippy.filling()) # Prints False
The color()
method is used to change pen color and fill color as shown below.
import turtles=int(input("Enter the side of a Square\n>>> "))scr = turtle.getscreen()flippy = turtle.Turtle()flippy.begin_fill()flippy.color("black", "red") # black: pen color; red: fill colorprint(flippy.filling()) # Prints Truefor i in range(4):flippy.fd(s)flippy.lt(90)flippy.end_fill()print(flippy.filling()) # Prints False