Draw basic shapes in turtle package in Python

I am going to demonstrate on  how draw basic geometric shapes using turtle package of python. First of  all the turtle package should be installed. Then we need to import turtle package into your python script.

Use the given below command.

import turtle

Turtle package is ready to use. Now you need to create object in Turtle.

turtle = Turtle()

Turtle is like a pen in your hand. Therefore you need to lift the pen to draw something. Use following command. to to up the pen.

turtle.up()

Move your pen to desired position. you need to define the place where your pen moves to.

turtle.goto(0,0)

I moved my pen to (0,0) coordinate. Now I am ready to draw something using my turtle pen. Now I am going to draw straight line. I am starting my line from point (0,0) and ending my line at point (100,100)

turtle.goto(100,100)

Then I need to tell my turtle pen to down to my canvas.

turtle.down()

Before drawing I need to set my pen width. I set my pen width to 5.

turtle.width(width=5)

Draw Straight line,

#!/usr/bin/python

import turtle
turtle = turtle.Turtle () turtle.up() turtle.goto(0,0) turtle.down () turtle.goto(100.,100) turtle.width(10

Now We can Draw simple circle.  To draw a circle we need starting point as well as radius. I am going to use following set of commands to draw circle.

#!/usr/bin/python

import turtle

turtle = turtle.Turtle ()

turtle.up() turtle.goto(0,0) turtle.down () turtle.circle(100) turtle.width(10)
I need to fill my Circle with Blue colour and line colour should be black.

#!/usr/bin/python

import turtle
turtle = turtle.Turtle ()
turtle.up() turtle.color("black","blue") turtle.goto(0,0) turtle.begin_fill() turtle.down () turtle.circle(100) turtle.width(10) turtle.end_fill()

begin_fill and end_fill functions are used to start and end fillings.


Draw rectrangle in turtle.

#!/usr/bin/python

import turtle

turtle = turtle.Turtle ()
turtle.color("blue") # line colour turtle.up() turtle.goto(0,0) # starting point turtle.down() turtle.forward(90) turtle.right(90) turtle.forward(100) # length of rectrangle turtle.right(90) turtle.forward(90) turtle.right(90) turtle.forward(100) # width of rectrangle


forward function is used to move pen forward to specific distance and right function is used to turn pen to right side by given angle . As well as there is left functions also. It used to turn your pen to left side by given angle.

#!/usr/bin/python

import turtle

turtle = turtle.Turtle ()
turtle.color("blue") # line colour turtle.up() turtle.goto(0,0) # starting point turtle.down() turtle.forward(200) turtle.left(120) turtle.forward(200) turtle.left(120) turtle.forward(200) turn.left(120)


Now you can draw basic shapes using turtle graphics. Try to draw complex figures !

Cheers !!!





0 comments:

Post a Comment

Ask anything about this Tutorial.