How to write text in turtle graphics in python
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.
from turtle import * write("Hello there!")
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.
write(arg, move=False, align="left", font=(fontname, fontsize, fonttype))
- arg – It is a text to display on the canvas and it should be string data type.
- move – It is to deal with the turtle/shape.
- if the move is set to True, the turtle or shape will move along the text
- if the move is set to False, the turtle or shape will stay ideal.
- 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.
- font – the font paramter can take three arguments ie. fontname, fontsize and fonttype.
- fontname can be any fontstyle accepted by the turtle graphics
- fontsize is a size of the text
- 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.
from turtle import * hideturtle() write("Hello there!", align="center", font=("Cooper Black", 25, "italic"))
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:
- Turtle window control
- Drawing shapes in turtle
- Filling color in shapes
- Accepting input in turtle canvas
- Events in turtle