All right, this is just a little tutorial about working with text in pygame. Now, this isn’t the only way to work with text, there are many other methods to do this, in fact much of the time you’ll probably end up using images for interactive text. So this is mainly meant to serve as a informative guide to using the text features in PyGame, and how you might want to implement them.
The TextWidget object discussed in this tutorial can be used to make something that looks like this (but you’d probably want to use better looking colours):
The full source and necessary files for this tutorial can be downloaded here.
So, in order to make this easy to use and very reusable we’re going to create a class called TextWidget in a file called TextWidget.py. The top of the file is full of the standard python initialization:
TEXT_WIDGET_CLICK = pygame.locals.USEREVENT + 1
We import pygame and then we set a define TEXT_WIDGET_CLICK , which will be used later on as the event type when the TextWidget is clicked on.
The next thing to do is define the actual class:
Now the astute among you will recognize that this is a “new-style” python class (i.e. it’s base class is the object class) rather then a classic class. I did this for two reasons:
- I wanted to be able to control what happens when people set values in the class. So, for example, if you set the size of the font to be something, I wanted the display to automatically adjust to reflect the new size.
- I haven’t really used new-style classes before so I thought I’d try them out.
Note: If you are unfamiliar with properties or new-style classes you might want to give this a read:
Continue reading TextWidget – A simple text class for PyGame