Turtle the 2D Python graphics module.
Making a new Turtle instance
1
2
3
4
5
|
# This however "clutters" the current namespace
from turtle import *
# Thus it's always recommended to use
import turtle as t
|
Using import turtle as t
(line 5) also allows us to have multiple turtle instances, like…
1
2
3
4
5
6
7
|
# Makes 2 instances, t1 and t2
import turtle as t1
import turtle as t2
# Simply causes t1 to move forward, while t2 moves backwards
t1.forward(100)
t2.backward(100)
|
Movement
1
2
3
4
5
6
7
8
9
|
import turtle as t
# Forward and Backward
t.forward(100)
t.backward(100)
# Left and Right Spin
t.left(90)
t.right(90)
|
The Turtle Pen
Our little turtle cares a pen. This allows us to draw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import turtle as t
# Changing the Color
t.color('blue')
# Changing the width
t.width(3)
# Bringing the pen Up and Down
t.up()
t.down()
# Filling, the pen width excluding the edges
t.fillcolor('yellow')
# Begin filling
t.begin_fill()
# Ends filling, fill only occures once end_fill is called
t.end_fill()
|
1
2
3
4
5
6
7
8
9
10
11
|
import turtle as t
# Getting the turtle's position
pos = t.pos()
print(pos) # Printing that out
# Move the turtle back to "home" (0, 0)
t.home()
# Clear the screen/window of Pen drawlings
t.clearscreen()
|
Turtle within a Python script
Once all turtle is done, Python closes the window, to keep it open…
1
2
3
4
5
6
7
8
9
10
11
|
# Make an instance
import turtle as t
# Itterate 10 times
for i in range(10):
# Turn left 170 degrees, and then move forward 200
t.left(170)
t.forward(200)
# Keeps the turtle window open
t.mainloop()
|