Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pygame - How to display text with font & color?

Tags:

python

pygame

Is there a way I can display text on a pygame window using python?

I need to display a bunch of live information that updates and would rather not make an image for each character I need.

Can I blit text to the screen?

like image 576
Max Hudson Avatar asked Apr 09 '12 18:04

Max Hudson


People also ask

How do I add a font to pygame?

You can load fonts from the system by using the pygame. font. SysFont() function.

How do you display text on screen in Python?

In python, the print statement is used to display text. In python with the print statement, you can use Single Quotes(') or Double Quotes(").


2 Answers

Yes. It is possible to draw text in pygame:

# initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error myfont = pygame.font.SysFont("monospace", 15)  # render text label = myfont.render("Some text!", 1, (255,255,0)) screen.blit(label, (100, 100)) 
like image 150
veiset Avatar answered Sep 19 '22 09:09

veiset


You can use your own custom fonts by setting the font path using pygame.font.Font

pygame.font.Font(filename, size): return Font 

example:

pygame.font.init() font_path = "./fonts/newfont.ttf" font_size = 32 fontObj = pygame.font.Font(font_path, font_size) 

Then render the font using fontObj.render and blit to a surface as in veiset's answer above. :)

like image 41
Technohazard Avatar answered Sep 21 '22 09:09

Technohazard