Search on blog:

PyGame: Wyświetlenie obrazka na ekranie

Najpierw trzeba wczytać obrazek

image = pygame.image.load('image.jpg')

Następnie trzeba wysłać obrazek do bufora (który reprezentuje powierzchnię ekranu/okna)

screen.blit(image, (0, 0))  # draw in buffer

Na koniec należy wysłać bufor na ekran/okno (po narysowaniu wszystkich elementów w buforze)

pygame.display.flip()  # send buffer on screen

PyGame używa podwójny bufor (double buffering) aby zapobiegać mruganiu ekranu (image flickering)

Dla pojedyńczego statycznego obrazka można to zrobić przed główną pętla/pętla obsługi zdarzeń (mainloop/event loop)

#import sys
import pygame

# --- constants --- (UPPER_CASE_NAMES)

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

# --- main --- (lower_case_names)

pygame.init()
screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )

image = pygame.image.load('/home/furas/Obrazy/images/image.jpg') 

screen.blit(image, (0, 0))
pygame.display.flip()

# --- mainloop ---

running = True
while running:

    # --- events ---

    for event in pygame.event.get():
        if event.type == pygame.QUIT: # exit on clicking button [X]
            running = False

# --- end ---

pygame.quit()
#sys.quit()

Ale normalnie używa się tego wewnątrz głównej pętli aby zmieniać obrazek lub inne elementy w celu tworzenia animacji.

#import sys
import pygame

# --- constants --- (UPPER_CASE_NAMES)

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
FPS = 25 # frames per seconds

# --- classes --- (CamelCaseNames)

# empty

# --- functions --- (lower_case_names)

# empty

# --- main --- (lower_case_names)

pygame.init()
screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )

image = pygame.image.load('image.jpg') #.convert()

# --- mainloop ---

clock = pygame.time.Clock()

running = True
while running:

    # --- events ---

    for event in pygame.event.get():
        if event.type == pygame.QUIT: # exit on clicking button [X]
            running = False

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_ESCAPE: # exit on pressing ESC
                running = False

    # --- draws ---

    screen.fill(BLACK) # clear screen
    screen.blit(image, (0, 0)) # draw in buffer
    pygame.display.flip() # send buffer on screen

    # --- FPS ---

    clock.tick(FPS) # slow down to 25 FPS

# --- end ---

pygame.quit()
#sys.quit()
If you like it
Buy a Coffee