I Like Turtles.
As my loyal blog readers have now learned, I am slowly becoming Python’s number one fan. But, did you know that Python is also friends with another reptile? Introducing: Turtle.
The Turtle module is a Graphical User Interface (or GUI) that you can import and use in your Python projects. The documentation calls it “a popular way for introducing programming to kids” but I would say adults like fun things too and this is a great resource for visual learners and people getting started with the concepts of Object-Oriented Programming in Python.
The great thing about Turtle is, unlike some other Python packages, it’s already on your machine! No need hunting it down and making sure it’s downloaded; if you have Python downloaded on your computer it is included and you are good to go.
Step 1: Import Turtle
The module may be downloaded, but you still need to import it into your file. Do it at the top of your file like so:
from turtle import Turtle, Screen
Turtle and Screen are the two Classes we will be using today, so that’s all we need to import for now.
Step 2: Make a Turtle
The first thing we need to do is to make our turtle. To do so, we need to call on the Turtle class, followed by two parentheses to signal that we want to build a new instance of the Turtle class.
arthur = Turtle()
Step 3: Make a Screen
Now that arthur has been brought into existence, we also need to build a screen so we can get a good look at him! This is when we use the Screen class.
screen = Screen()
Step 4: Keep Screen Open
If you run the code just as is now, you will see a quick flash of the screen and that’s it. What gives? Well, we need to use a special Screen method that will make sure that the screen will only close when we click on the exit, like so:
Now, we can get a good look at our turtle:
Hmm…Arthur sure isn’t very turtle-y. Let’s get to fixing that!
Arthur the turtle has lots of fun things he can do! Let’s get started with spiffing him up a bit.
Like we see above, Arthur is…well, he’s not a turtle. We can change that with the Turtle.shape() method. Check out the documentation to see all of your options, but today I’m going to give Arthur a classic turtle shape, using the string ‘turtle’ as my parameter inside the method.
Look at that cute guy! Now it’s time to brighten him up a bit.
Turtle.color() is a method similar to the shape method we discussed above, that takes a string of a color name as its argument and will then change that turtle into said color. I’m gonna go classic and give Arthur a green color:
Look at that guy! Now he’s all spiffed up and ready for his day.
These are the basics of the Turtle package, but there is so much you can do with this guy — he can travel all over the screen, he can make art, he can place dots — there are lots of ways to make really cool and creative projects very simply…maybe next time we’ll build a fun project together? For now explore the really helpful documentation…happy coding!