Hi there, today we will be talking about something interesting as well as simple. In this tutorial we will understand what the python turtle module is and will learn about turtle programming in python in detail.
So, let’s get started.
Requirements
Basic knowledge of python(go through Learn Python Tutorial) . We can use any ide ( for example: https://code.visualstudio.com/download , https://jupyter.org/).
Introduction:
Turtle module: It is a python inbuilt module similar to a canvas that lets us command a turtle to draw attractive pictures and shapes on it.
Installation:
It is an inbuilt module ,so we do not have to install it.
Approach for turtle programming:
1. Firstly, we have to import the module .
import turtle
2. Secondly, we will create a graphics window and color on it.
MyWindow = turtle.Screen() MyWindow.bgcolor("white")
3. Thirdly, we have to create a turtle object.
MyPen = turtle.Turtle()
4. Now, we will learn some useful methods so that we can draw in the graphics window.
A.forward()
: It takes amount as its parameter and moves the turtle forward by that amount.
B.backward()
: It moves the turtle backward by the amount, it takes as parameter.
C.right() , left() :
It turns the turtle clockwise and counter clockwise, respectively by the angle they take as the parameter.
D.up() ,down() :
It picks up and put down the turtle pen respectively.
E.color() & fillcolor()
: The first one changes the color of the pen and the second one helps us to fill color in a polygon. The parameters in both cases are colors.
F.goto()
: It takes (x,y) as its parameter and moves the turtle to x,y .
Example Code for Turtle Programming :
1(draw a square) :
import turtle t = turtle.Turtle() for i in range(4): t.forward(50) t.left(90)
2(draw a hexagon) :
import turtle ws = turtle.Screen() MyTurtle = turtle.Turtle() for i in range(6): MyTurtle.forward(90) MyTurtle.left(300)
3(draw Olympic Symbol) :
import turtle t = turtle.Turtle() t.pensize(5) t.color("blue") t.penup() t.goto(-110, -25) t.pendown() t.circle(45) t.color("black") t.penup() t.goto(0, -25) t.pendown() t.circle(45) t.color("red") t.penup() t.goto(110, -25) t.pendown() t.circle(45) t.color("yellow") t.penup() t.goto(-55, -75) t.pendown() t.circle(45) t.color("green") t.penup() t.goto(55, -75) t.pendown() t.circle(45)