PyGame: Draw image on screen
First you have to load image
image = pygame.image.load('image.jpg')
Next you have to send image to buffer (which represents screen/window surface)
screen.blit(image, (0, 0)) # draw in buffer
And finally you send buffer on screen/window (after you draw all elements in buffer)
pygame.display.flip() # send buffer on screen
PyGame uses double buffering to prevent image flickering
For single static image you could do it before mainloop
#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()
But normally it is used inside mailoop so in every loop you can change image or other elements to make animation.
#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
