Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Hiển thị văn bản trên Pygame Window Python

Mô tả

Hiển thị text tùy chỉnh font, màu, vị trí trên cửa sổ Pygame.

Code hoàn chỉnh

import pygame
import sys

pygame.init()

# Cửa sổ
sur_obj = pygame.display.set_mode((300, 200))
pygame.display.set_caption("Text in Pygame")

# Màu font
font_color = (0, 150, 250)

# Load font - dùng font hệ thống hoặc file .ttf
# Windows: C:\Windows\Fonts\segoeprb.ttf
# Linux: /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf
# Mac: /System/Library/Fonts/Helvetica.ttc
try:
    font_obj = pygame.font.Font(r"C:\Windows\Fonts\segoeprb.ttf", 25)
except:
    font_obj = pygame.font.SysFont('Arial', 25)  # Fallback

# Render text thành Surface
text_obj = font_obj.render("Welcome to Pygame", True, font_color)

# Vòng lặp
while True:
    sur_obj.fill((255, 255, 255))  # Clear màn hình
    sur_obj.blit(text_obj, (22, 0))  # Vẽ text tại (x, y)
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    
    pygame.display.update()

Giải thích các bước

  1. pygame.font.Font(file, size): Load font từ file .ttf/.otf.
  2. pygame.font.SysFont(name, size): Load font hệ thống theo tên.
  3. font.render(text, antialias, color, bg_color=None): Tạo Surface chứa text.
    • antialias=True: Làm mượt cạnh chữ (khuyên dùng).
    • Trả về Surface, không vẽ trực tiếp lên màn hình.
  4. surface.blit(source, dest): Vẽ source surface lên destination tại tọa độ dest.

Font phổ biến cross-platform

# Tìm font có sẵn
import pygame
pygame.font.init()
fonts = pygame.font.get_fonts()
print(fonts[:10])  # ['arial', 'dejavusans', 'freesans', ...]

# Dùng font an toàn
font = pygame.font.SysFont('dejavusans', 24)

Căn chỉnh text

text_surface = font.render("Text", True, (0,0,0))
text_rect = text_surface.get_rect()

# Căn giữa màn hình
text_rect.center = (width//2, height//2)
screen.blit(text_surface, text_rect)

# Căn trái, giữa dọc
text_rect.midleft = (10, height//2)
screen.blit(text_surface, text_rect)