Start New Discussion within our Software Development Community

This simple code shows how to write text with a given font, font size and color using the module pygame ...

# a simple pygame text example
# vegaseat

import pygame as pg

pg.init()

# use a (r, g, b) tuple for color
yellow = (255, 255, 0)

# create the basic window/screen and a title/caption
# default is a black background
screen = pg.display.set_mode((640, 280))
pg.display.set_caption("Text adventures with Pygame")
# pick a font you have and set its size
myfont = pg.font.SysFont("Comic Sans MS", 30)
# apply it to text on a label
label = myfont.render("Python and Pygame are Fun!", 1, yellow)
# put the label object on the screen at point x=100, y=100
screen.blit(label, (100, 100))
# show the whole thing
pg.display.flip()

# event loop
while True:
    for event in pg.event.get():
        # exit conditions --> windows titlebar x click
        if event.type == pg.QUIT:
            raise SystemExit

I took the liberty of improving the code above to make it easier to reuse. I release this code as is under GPL version 2 license. Please credit me if you use this code.

# a simple pygame text example by vegaseat and extended by lee allen
import pygame   
pygame.init()
     
# use a (r, g, b) tuple for color
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
yellow = (255, 255, 0) 
    
# create the basic window/screen and a title/caption
# default is a black background
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Text adventures with Pygame")

def printText(txtText, Textfont, Textsize , Textx, Texty, Textcolor):
	# pick a font you have and set its size
	myfont = pygame.font.SysFont(Textfont, Textsize)
	# apply it to text on a label
	label = myfont.render(txtText, 1, Textcolor)
	# put the label object on the screen at point Textx, Texty
	screen.blit(label, (Textx, Texty))
	# show the whole thing
	pygame.display.flip()

#printText(Text, Font, Size, X, Y, Color)
printText("Hello World", "MS Comic Sans", 30, 10, 10, red)
printText("Hello World", "MS Comic Sans", 30, 10, 30, green)
printText("Hello World", "MS Comic Sans", 30, 10, 50, blue)
printText("Hello World", "MS Comic Sans", 30, 10, 70, yellow)

Thank you,
Lee Allen

it's kinda improper for you to say that things lsallen, because daniweb is a free source code website, so, I don't think that any1 will 'steal' your code and sell it on ebay...

sorry its a force of habit i used it be into making source code that was my hidden secret that was until i found out about and started to use linux

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.