Strings in Turtle Graphics

Using Strings In Turtle

We can use the turtle package to write text to the screen. Copy and past the following code into a new files called SpiralMyName.py

# SpiralMyName.py - prints a colorful spiral of the user's name

import turtle               # Set up turtle graphics
t = turtle.Pen()
t.speed(0)
turtle.bgcolor("black")
colors = ["red", "yellow", "blue", "green"]

# Ask the user's name using turtle's textinput pop-up window
your_name = turtle.textinput("Enter your name", "What is your name?")

# Draw a spiral of the name on the screen, written 100 times
for x in range(100):
    t.pencolor( colors[ x % 4] )
    t.penup()
    t.forward( x * 4 )
    t.pendown()
    t.write(your_name, font = ("Times", int( (x + 4) / 4), "bold") )
    t.left(92)

There are a few lines here that are new:

your_name = turtle.textinput("Enter your name", "What is your name?")

Because we are displaying the turtle screen, we need to use the turtle.textinput

t.penup()
t.forward( x * 4 )
t.pendown()

t.penup() lift the pen from the screen so that nothing is drawn. We then move it forward with t.forward() before putting the pen back down with t.pendown()

t.write(your_name, font = ("Times", int( (x + 4) / 4), "bold") )

t.write is the command used to write text to the turtle screen.

The font key-word argument takes the variables font = ( [font_name], [font_size], [font_weight]) so here we are using the Times New Roman font with an increasing font size in bold.

You can also use Arial and Courier as fonts

Last updated

Was this helpful?