Turtle Graphics in Python

turtle

Can you imagine to draw pictures using programming? Are you a good artist? Are you a good programmer? Then try to be both an artist and a programmer by using turtle graphics in python.

Turtle in Python

Turtle is one of the python modules which draws according to the commands specified by the user.

Steps to run a Turtle

  • Import turtle module in order to access all the functions of turtle for drawing.
  • Create a new turtle and assign it a desired name.
  • Use turtle commands to draw desired shapes.
  • Run the code and view output.

Turtle direction commands

  • To move backward.
import turtle
myturtle= turtle.Turtle()
turtle backward
myturtle.backward(40)	
turtle.done()
  • To move forward.
import turtle
myturtle= turtle.Turtle()
turtle forward
myturtle.forward(40)	
turtle.done()
  • To draw a rectangle.
import turtle
myturtle= turtle.Turtle()
myturtle.forward(100)
myturtle.right(90)
myturtle.forward(50)
myturtle.right(90)
myturtle.forward(100)
myturtle.right(90)
myturtle.forward(50)
turtle.done()
  • To draw rectangle in an optimized way.

import turtle
myturtle= turtle.Turtle()

for i in range(2):
             myturtle.forward(100)
             myturtle.right(90)
             myturtle.forward(50)
             myturtle.right(90)

turtle.done()
  • To draw a colored star spiral.
import turtle
myturtle= turtle.Turtle()
myturtle.pencolor("red")
for i in range(10):
             myturtle.forward(50)
             myturtle.left(100)
myturtle.pencolor("black")
for i in range(10):
             myturtle.forward(50)
             myturtle.left(100)

turtle.done()

Functions of Turtle

  • Turtle()          – To create a new turtle object and return an object.
  • forward()      – To move the turtle forward by some amount.
  • backward()  – To move the turtle backward by some amount
  • right()            – To turn the turtle clockwise
  • left()               – To turn the turtle anti-clockwise.
  • penup()         – To pick the turtle’s pen.
  • pendown()   – To drop the turtle’s pen.
  • position()     – Returns the current position.
  • goto()            – Moves the position of turtle to specified (x,y) value.
  • pencolor()   – chooses the color of pen to draw.
 

Use these functions to draw any simple shapes or even complex shapes.You can also discover new shapes of your own by making your own commands to turtle.Try making spirals of shapes too.Hope this post would have introduced basics of turtle graphics in python.Try the advanced features soon.

Leave a Reply

Your email address will not be published. Required fields are marked *