Whether you need to show off the numbers for a sales presentation or the number of aliens obliterated, there are times where you'll want to display text on a graphics screen. The games module contains a class that allows you to do just that, aptly named Text.
Displaying text on a graphics window is just a matter of creating an object of the Text class. In the Big Score program, I add some text to the graphics window to display a score in the upper-right corner of the screen, just like in many classic arcade games. Figure 11.6 shows the results.
Figure 11.6: The impressively high score is displayed after a Text object is instantiated.
This Big Score program builds on the Background Image program. I add just one line of code and modify another.
The livewires package contains another module, color, which has a set of constants that represent different colors. These colors can be applied to certain graphics objects, including any Text or Message object. For a complete list of predefined colors, see the livewires documentation in Appendix A.
To choose from a group of possible colors, I import the color module by modifying the import line like so:
from livewires import games, color
Now, both the color and games modules are loaded from the livewires package.
A Text object represents text on a Screen object. A Text object has attributes for x- and y-coordinates, a font size, a color, and some text too, of course.
In the Big Score program, I use a Text object to represent a game score. Just before I invoke the Screen object's mainloop() method, I create a Text object through the following code:
games.Text(screen = my_screen, x = 500, y = 30, text = :Score: 1756521", size = 50, color = color.black)
The constructor method for a Text object requires the following values: a Screen object, x- and y-coordinates, a string, a font size, and a color, as shown. I pass my_screen to screen since that's the active graphics window. Next I pass 500 to x and 30 to y, placing the center of the object at the coordinates (500,30). This puts the text in the upper-right corner of the graphics window. I pass the string "Score: 1756521" to text so that those characters will be displayed. Then I pass 50 to size so the font is nice and big, to match the score. Finally, I pass color the constant color.black from the color module to make the text, you guessed it, black.
You may have noticed that I don't assign the new Text object to a variable. That's okay since the the Screen object, my_screen, is designed to keep track of all of the graphics objects (just as a root window in a Tkinter program holds references to all of its widgets).
Once my_screen's mainloop() method is invoked, the graphics window is displayed along with the new Text object.