Monday, April 21, 2025

Python Turtle - Forward, Backward, Angles, Directions

This tutorial is all about angles and paths. It's a little bit more computational demanding because we need to think about turtle (object) rotation to reach ending point.

Make sure that this source work on you machine:

import turtle

t = turtle.Turtle()

t.left(45)
t.fd(400)
t.left(135)

t.fd(600)
t.left(90)
t.fd(600)

t.left(90)
t.fd(600)

t.left(90)
t.fd(600)

t.hideturtle()

 

As with last tutorial, first module import and turtle (object) creation:

import turtle

t = turtle.Turtle()

Then we are rotating a turtle for 45 degrees to the left side using left() method:

t.left(45)

Still from a centre of coordinate system we are going forward for 400 pixels, to rach point in upper right position:

t.fd(400)

When we reach it, we will rotate again to left side for 135 degrees, because we need to sent turtle in next step for 600 pixels to try to create one horizontal line, parallel to x axis:

t.left(135)

After that you can experiment with angles and paths to get box with equal sides, but this will work:

t.fd(600)
t.left(90)
t.fd(600)

t.left(90)
t.fd(600)

t.left(90)
t.fd(600)

And if there is need to hide turtle object we can always do that with hideturtle() method:

t.hideturtle()

Line / Path Colors

From last tutorial we know how to set colors for shapes.

In this case, we can use begin_fill() method to paint lines. When a specific point is reached, a turtle change colors. Please note, theres no usage of end_fill() method, because we are painting just path, not whole shape defined by a path:

import turtle

t = turtle.Turtle()
t.color("red")
t.begin_fill()
t.left(45)
t.fd(400)
t.left(135)

t.color("green")
t.fd(600)

t.color("black")
t.left(90)
t.fd(600)

t.color("magenta")
t.left(90)
t.fd(600)

t.color("navy")
t.left(90)
t.fd(600)

t.hideturtle()


You are advised to check corresponding YouTube tutorial on Turtle Methods, Angles and Directions.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...