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.

def draw_pen():
window.exitonclick()
draw_pen()

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( ).

def draw_pen():
listen()
onkey(goFoward, "Up")
window.exitonclick()
def goFoward():
pen.foward(30)
draw_pen()

pen.foward(30) means that your pen will move 30 pixels and draw a line in the direction it is facing.

It is alive! And probably you will never see your pen ever again.

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:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store