Turtle Module in Python

 

Turtle Module in Python

For a better reading experience, check the published document


What is turtle?

This module can create a virtual turtle that comes with a white canvas. This turtle can move or draw on the canvas with your guidance as coded instructions.

We can also edit the configurations of both the turtle and the canvas to customize our art.


 

Installing the module

This module is a built-in module, so no need to install it.


 

Importing the module

We use the (*) to import all classes in the module

from turtle import *


 

Set up the aquarium for ted

Let’s write some required code to make the turtle “ted” draw

Create a turtle object and name it “ted“, then define the finishing line where ted will stop

ted = Turtle()  # ted the turtle

# your code will be written here

done()  # finishing line


 

Modifying ted’s attributes

We can modify a lot of ted’s attributes:


Drawings (trail) of ted

when ted move, he will leave a trail of color behind him on the canvas

ted.color("red")                # change the color of ted's frame and its drawings to red
ted.color("red", "green")       # change the color of ted's filling to green

ted.color("#15fa53", "#54bc2f") # use hexa values to change colors

colormode(255)             # change the color input mode to be RGB instead of the default "None"
ted.color((40, 80, 120), (160, 200, 240)) # use RGB values to change colors

ted.width(5)                    # change the width of the line that ted will draw to (5) pixels


Visibility of ted

we can hide/show ted on the screen

ted.hideturtle()  # hide ted from the screen
ted.ht()          # alias of the previous line (do the same)

ted.showturtle()  # show ted on the screen
ted.st()          # alias 


Pen of ted

we can make ted stop/start drawing on the canvas by controlling his pen

ted.penup()   # hold ted's pen up, so he won’t be able to draw anything, but he is free to move ted.pu()      # alias 

ted.pendown()   # put ted's pen down, so he will be able to draw when he moves
ted.pd()        # alias 

ted.pen('pensize': 10, 'pendown': True, 'speed': 3)   # change attributes of ted's pen 

ted.pen()       # return the pen's current attributes:
#    {'pensize': 10, 
#     'shown': True, 
#     'resizemode': 'auto', 
#     'outline': 1,
#     'pencolor': 'yellow', 
#     'pendown': True, 
#     'fillcolor': 'black',
#     'stretchfactor': (1,1), 
#     'speed': 3, 
#     'shearfactor': 0.0}


Speed of ted

we can change his speed where 0 is the fastest, 1 is the slowest, then we have an increasing scale of speed (2, 3, 4, ...)

ted.speed(5)    # change ted's speed to be (5)
ted.speed(0)    # change ted's speed to be the fastest


Angle system of ted

we can change the measuring unit of ted’s angle (where his head points) between degrees and radians

ted.degrees()   # set the angle unit of ted to "degrees"
ted.radians()   # set the angle unit of ted to "radians"


Shape of ted

change the symbol that represents the turtle ted

ted.shape(“turtle”)   # give a shape of a (turtle) to ted instead of the default (arrow)
ted.shape(“arrow”)    # give a shape of an (arrow)

Available shapes: 'classic', 'arrow', 'turtle', 'circle', 'square', 'triangle'


 

Make ted move, draw, and speak

While moving, if the pen was down, ted will leave a trail on the canvas as he moves (it will draw)

Moving in 4 directions

ted.forward(100)    # draw a 100 pixels line with its current direction (forward) 
ted.fd(100)         # alias 

ted.backward(100)   # draw a 100 pixels line in the opposite direction (backward) 
ted.bk(100)         # alias 6                    
# no rotation, only moving backward with keeping the direction of the arrow 

ted.right(70)       # make a rotation of 70 degrees clock-wise (the right of the arrow) 
ted.rt(70)          # alias 

ted.left(70)        # make a rotation of 70 degrees counter clock-wise (the left of the arrow) 
ted.lt(70)          # alias


Moving to a specific point

ted.goto(50, 80)        # teleport ted to that position (x, y) which is (50, 80) 
ted.towards(200, 300)   # turn the angle of the turtle towards that point (x, y)  
ted.home()              # move ted to the origin point (0, 0)  


Cloning ted

make and return a clone of the turtle at its current location, so it can move as another turtle

mark = ted.clone()   # clone ted and now we have two turtles (ted & mark)


Built-in shapes

ted can draw some pre-defined shapes

ted.dot(20, "white")    # draw a white dot with a size of 20 at ted’s current position

ted.circle(60)          # draw a circle with a radius of 60

ted.circle(radius=80, extent=180, steps=6)
# draw a closed shape with a radius of 80 with 6 sides spreaded half a circle (180), 
# we can decide the spreading area by the angle at "extent" (0 and above, even more then 360)


Make ted speak

we can make ted leave an annotation at his current positions with the same color of his drawings

ted.write("hello")    # ted will drop a note that says "hello"


Filling ted’s closed shapes (shading)

we can fill the closed shapes by giving a start command just before ted start drawing the shape, and an end command just after he finished it, and the desired shape doesn't necessarily be closed

ted.begin_fill()     # start command: just before start
ted.end_fill()       # start command: just after finished

ted.filling()   # return the state of filling (check if the filling process is active or not)

ted.fillcolor("red") 
# set the color  of the filling (must be assigned before or during the filling process)

ted.fillcolor("")       # erase the color of filling (make it transparent)


 

Linking functions with ted

Built a custom function for ted

we can define some repeated moves for ted in a function, then call it whenever we want ted to draw the shape we have defined

def draw_stairs(turt) 
    for _ in range(5): 
   	    turt.fd(50) 
        turt.rt(-90) 
        turt.fd(50) 
        turt.rt(90) 

draw_stairs(ted)   # make ted draw 5 stairs


Bind (link) the mouse’s buttons with ted

we can customize what should ted do if we click on him with one of the mouse’s buttons

def say_hello(x, y):
    turt.write("hello")

ted.onclick(say_hello, 1)
# trigger the function (say_hello) whenever we left-click on ted,
# and send his current position as (x, y) to it

ted.onrelease()
# trigger the function (say_hello) whenever we release the click on ted

ted.ondrag(ted.goto)
# trigger the function (goto) whenever we drag ted, which will drag him with 
# the mouse movement as long as we don't release him

we use numeric representation for the buttons as the following:

1: left-click

2: roller-click

3: right-click


 

Investigate about ted

Position of ted

we can see where is ted’s position as an (x, y) coordinates

ted.xcor()              # return ted's x-coordinate on the canvas  
ted.ycor()              # return ted's y-coordinate on the canvas 
ted.pos()               # return ted's current location (x, y)


The relative position of ted

we can see the distance between ted and a point on the canvas

ted.distance(0,300)     # return the distance from ted's position to this point


 

Window/Canvas configurations

Playing with the canvas

changing some of the attributes of the canvas

ted.reset()   # delete all ted's drawings and return him to its default position  
ted.clear()   # only delete the drawings 
ted.undo()    # undo that last ted's action


Control the window’s attributes

we can define the current window as a variable so we can control its attributes

win = Screen()        # define the current screen 2win.bgcolor("red")    # change the background color of the screen to (red)3win.exitonclick()     # close the window once you click on it

Comments