How to write text in turtle graphics in python



Introduction

We know that turtle in python usually deals with graphics. However, we can also write text in a turtle. To display a text on a turtle canvas or in a turtle window we use a method called write().

write() method in turtle

write() method of a turtle module is used to display text in a turtle window. The simple and plain way to display text is to just pass a string argument inside the write method.

For example:

from turtle import *
write("Hello there!")

Output:

text in turtle

However, the above simple way of writing text in turtle does not provide flexibility for customization. Hence, the write method takes in four optional parameters to format the text displayed on the canvas.

Syntax:

write(arg, move=False, align="left", font=(fontname, fontsize, fonttype))


Parameters:

  1. arg – It is a text to display on the canvas and it should be string data type.
  2. move – It is to deal with the turtle/shape.
    1. if the move is set to True, the turtle or shape will move along the text
    2. if the move is set to False, the turtle or shape will stay ideal.
  3. align – It is to align the text or the argument you have passed inside the write() method. You can assign either left, right, or center as its value.
  4. font – the font paramter can take three arguments ie. fontname, fontsize and fonttype.
    1. fontname can be any fontstyle accepted by the turtle graphics
    2. fontsize is a size of the text
    3. fonttype is the type of the font. It can be either bold, italic, or normal.

Now let’s look into the more customized text on the canvas passing all the arguments accepted by the write() method.

Example:

from turtle import *

hideturtle()
write("Hello there!", align="center", font=("Cooper Black", 25, "italic"))



Output:

write()

In the above example, I have not specified the move argument because I don’t want to see the movement of the turtle along the text drawn. Contrary, I have used the hideturtle() method to hide the turtle to keep the text clean on the canvas. However, if you want to see the difference with the move arguments, you may check by passing an additional argument ie. move = True. it should work perfectly fine.


Other related article on turtle:

  1. Turtle window control
  2. Drawing shapes in turtle
  3. Filling color in shapes
  4. Accepting input in turtle canvas
  5. Events in turtle