Drawing With Python
Python is a very friendly language, and it can be very entertaining even for young learners to use, so a good way to make your niece or nephew started on coding is by doing a project that is both easy to set and fun to use.
Turtle was specially created to introduce programming to kids but before you start, make sure you have Python installed by running the following command on your terminal/Windows Powershell:
$ python -V
You can check the complete code for this tutorial down below, but in the end, you will have something like this:
Creating our pen to draw
I created a file called turtleDraw.py and the first thing we will do is to import turtle on our app, for this project, we will only need the Turtle, Screen, onclick and listen function, you can also use * to import everything on Turtle.
from turtle import Turtle, Screen, onkey, listen
Next, we will create our pen using the Turtle function and our window with Screen:
window = Screen()
pen = Turtle()
I’m telling turtle to create a new screen called window, a pen, and next, I’m creating our main function where I’m saying the only way to exit our window is if the user clicks on it.
And on the command line run: python3 turtleDraw.py to execute the file and you should be prompted with a screen like this, and your file should look like this:
Make sure you are in the right directory (folder) before executing the file.
Now let’s make it move
Turtle already has built-in functions that will do all the heavy work for us, for this tutorial will only need to move forward, back, and be able to turn right and left, let’s start with a function that will make it go forward.
For this, we will need to set on our main function to listen to user input with listen( ) and create a function that will make our pen move, we will call it goFoward( ).
pen.foward(30) means that your pen will move 30 pixels and draw a line in the direction it is facing.
Now we will set up the rest of the other actions like this:
And you should be able to draw a beautiful shaped… thing.
You can see the complete code below:
There is a lot more you can do with Turtle, make sure to read the documentation to see everything it is capable of.
turtle - Turtle graphics - Python 3.8.3 documentation
Drawing state Pull the pen down - drawing when moving. Pull the pen up - no drawing when moving. Set the line thickness…
Fork this repo on my Github/etch-a-sketch
You can also read this in Portuguese! https://rmiriuk.medium.com/desenhando-com-python-fac7cbe2d454