Il y a deux possibilités. Dans les deux cas, PyGame doit être initialisé par pygame.init
.
import pygame
pygame.init()
Utilisez soit le pygame.font
et créer un module pygame.font.SysFont
o pygame.font.Font
objet. render()
a pygame.Surface
avec le texte et blit
le site Surface à l'écran :
my_font = pygame.font.SysFont(None, 50)
text_surface = myfont.render("Hello world!", True, (255, 0, 0))
screen.blit(text_surface, (10, 10))
Ou utilisez le pygame.freetype
module. Créez un pygame.freetype.SysFont()
o pygame.freetype.Font
objet. render()
a pygame.Surface
avec le texte ou directement render_to()
le texte à l'écran :
my_ft_font = pygame.freetype.SysFont('Times New Roman', 50)
my_ft_font.render_to(screen, (10, 10), "Hello world!", (255, 0, 0))
Voir aussi Texte et police
Minimal pygame.font
exemple : <a href="https://repl.it/@Rabbid76/PyGame-Text#main.py" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5jD0C.png" alt=""> repl.it/@Rabbid76/PyGame-Text</a>
import pygame
pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 100)
text = font.render('Hello World', True, (255, 0, 0))
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
pygame.draw.rect(background, color, rect)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.blit(background, (0, 0))
window.blit(text, text.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()
Minimal pygame.freetype
exemple : <a href="https://repl.it/@Rabbid76/PyGame-FreeTypeText#main.py" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5jD0C.png" alt=""> repl.it/@Rabbid76/PyGame-FreeTypeText</a>
import pygame
import pygame.freetype
pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()
ft_font = pygame.freetype.SysFont('Times New Roman', 80)
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
pygame.draw.rect(background, color, rect)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.blit(background, (0, 0))
text_rect = ft_font.get_rect('Hello World')
text_rect.center = window.get_rect().center
ft_font.render_to(window, text_rect.topleft, 'Hello World', (255, 0, 0))
pygame.display.flip()
pygame.quit()
exit()