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

Hiển thị hình ảnh trên Pygame Python

Mô tả

Load và hiển thị file hình ảnh (png, jpg, bmp) trên cửa sổ Pygame.

Code hoàn chỉnh

import pygame

pygame.init()

# Cửa sổ
w, h = 300, 300
screen = pygame.display.set_mode((w, h))
pygame.display.set_caption('Tutorialspoint Logo')

# Load ảnh
# .convert() tối ưu hóa cho hiển thị nhanh (chuyển pixel format khớp màn hình)
# .convert_alpha() nếu ảnh có độ trong suốt (alpha channel)
try:
    TPImage = pygame.image.load(r"E:\Python3\tutorialspoint.png").convert()
except pygame.error as e:
    print(f"Không load được ảnh: {e}")
    # Tạo surface màu thay thế
    TPImage = pygame.Surface((100, 100))
    TPImage.fill((255, 0, 0))

# Tọa độ vẽ (góc trên-trái của ảnh)
x, y = 10, 20
screen.blit(TPImage, (x, y))

# Cập nhật màn hình 1 lần
pygame.display.flip()

# Vòng lặp giữ cửa sổ
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

pygame.quit()

Chi tiết load ảnh

Phương thứcDùng khiHiệu năng
load()Load cơ bảnChậm hơn khi blit nhiều lần
load().convert()Ảnh không trong suốtNhanh nhất cho blit lặp lại
load().convert_alpha()Ảnh có alpha/transparencyNhanh, giữ độ trong suốt

Thao tác với ảnh

# Scale (thay đổi kích thước)
scaled = pygame.transform.scale(TPImage, (150, 150))

# Rotate (xoay)
rotated = pygame.transform.rotate(TPImage, 45)  # độ

# Flip (lật)
flipped_h = pygame.transform.flip(TPImage, True, False)  # ngang
flipped_v = pygame.transform.flip(TPImage, False, True)  # dọc

# Lấy kích thước
width, height = TPImage.get_size()
rect = TPImage.get_rect()  # rect dùng cho positioning, collision

Đường dẫn file

  • Windows: r"E:\path\image.png" (raw string tránh escape)
  • Relative path: "images/logo.png" (tương đối file script)
  • Dùng os.path.join hoặc pathlib.Path cho cross-platform.