Python comes with a module called turtle
that can be used to create simple graphics in a window on the computer screen.
Copy the program below, turtle_basics.py
, and run it. Then, play around with changing some of the values, and see what you can get the turtle to draw.
#!/usr/bin/env python3
"""
Some basic turtle commands, demonstrated.
"""
from turtle import *
win = Screen() # creates a window for the turtles "world"
tom = Turtle() # creates a turtle and places it in middle
tom.shape("turtle") # change default arrow to a turtle shape
tom.speed(2) # set to 0 to have turtle go as fast as possible
def draw_square(n):
for i in range(4):
tom.forward(n)
tom.left(90)
def main():
tom.fillcolor("blue") # sets color to fill in shapes
tom.begin_fill() # will begin fill process for shapes
draw_square(100)
tom.end_fill() # stops looking for shapes to fill
tom.penup() # stop drawing the turtles path
tom.goto(75, -25) # move to a new location on the screen,
# although turtle maintains, direction
tom.left(15) # rotate turtle 15 degrees to the left from
# current orientation
colormode(255) # allows for (R,G,B) color values
tom.pencolor((255,128,255)) # sets pen color to R,G,B value
tom.pensize(5) # specifies thickness of line
tom.pendown() # start drawing again
draw_square(100)
win.exitonclick() # keeps window from closing too soon
if __name__ == "__main__":
main()
If you want to explore the capabilities of the turtle
module more:
Start up a Terminal and open up an interactive Python session by entering python
.
$ python
Python 3.7.4 (default, Aug 13 2019, 15:17:50)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
Enter import turtle
into the interpreter.
>>> import turtle
>>>
Enter help(turtle)
You'll be able to view the documentation for the turtle
module in manual
mode, which uses special commands to navigate the documentation.
q
→ Quit^f
→ Go forward one page^b
→ Go back one pageG
→ Jump to end of documentgg
→ Jump to beginning of a document/searchterm
→ Jump to occurence of that termn
→ Find next occurence of that termN
→ Find previous occurence of that term?searchterm
→ Search backwards