On Sale: GamesAssetsToolsTabletopComics
Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
Tags

how can I import an image from my folder to the screen in pygame? (I am using vs code)

A topic by Yeetus_Codes created 25 days ago Views: 38 Replies: 1
Viewing posts 1 to 2

I do not know how to do it.

Host

Hey Yeetus! Next time if you want a faster response from a larger community you should join our Discord to ask questions! https://discord.gg/ZReu92VTCV

Loading the image:

import os

image_path = os.path.join("images", "your_image.png")  # Replace with your image filename

try:

    image = pygame.image.load(image_path)

except FileNotFoundError:

    print("Error: Image file not found!")

    quit()

Displaying the image:

screen.blit(image, (0, 0)) # Place the image at (0, 0) for top-left corner

Here is a complete example of the main.py:

import pygame

import os

pygame.init()

screen_width = 800

screen_height = 600

screen = pygame.display.set_mode((screen_width, screen_height))

image_path = os.path.join("images", "your_image.png")

try:

    image = pygame.image.load(image_path).convert_alpha()

except FileNotFoundError:

    print("Error: Image file not found!")

    quit()

running = True

while running:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            running = False

    screen.fill((0, 0, 0))

    screen.blit(image, (0, 0))

    pygame.display.flip()

pygame.quit()



Please tell me if you need any further help! And for more convenience in terms of sharing code, and reaching to a larger audience, I would highly suggest you join CougarCup's discord here: https://discord.gg/ZReu92VTCV