Home > Mobile >  I am trying to insert a sprite image into pygame window and it wont pop up
I am trying to insert a sprite image into pygame window and it wont pop up

Time:04-09

uhhhh (i followed a yt tut so idk) my code: idk if i put code in wrong place

import pygame
   
 white = (255,255,255)
 black = (0,0,0)
 orange = (255,165,0) 
 player_sprite = pygame.image.load("will smith.png") .convert_alpha


 pygame.init()
 display = pygame.display.set_mode((850,850))
 pygame.display.set_caption('Conners Game')

 exit = False

while not exit:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        exit = True
    print(event)

display.fill(white)
pygame.display.update()

pygame.quit()
quit()

not really sure why it does this, im new to python so idk

CodePudding user response:

There are multiple things that needs to fixed. First of all to you actually need to blit the image on the screen.

while not exit:

    for event in pygame.event.get():
        #...[block of code]

    display.fill(white)
    display.blit(player_sprite, (100,100)) # BLIT IMAGE TO SCREEN

.convert_alpha() is a method and you need to call it after you initialize pygame and set the video mode.

You can read more about convert_alpha() here

pygame.init()
display = pygame.display.set_mode((850,850))
pygame.display.set_caption('Conners Game')

#converting it after init and setting game mode

player_sprite = pygame.image.load("will smith.png").convert_alpha() 

Here's the final working code

import pygame
   
white = (255,255,255)
black = (0,0,0)
orange = (255,165,0) 



pygame.init()
display = pygame.display.set_mode((850,850))
pygame.display.set_caption('Conners Game')
player_sprite = pygame.image.load("will smith.png").convert_alpha()
exit = False

while not exit:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit = True
        # print(event)

    display.fill(white)
    display.blit(player_sprite, (100,100))
    pygame.display.update()

pygame.quit()
quit()

CodePudding user response:

You have to blit the image in the application loop, after clearing the display and before updating the disaply:

display.blit(player_sprite, (100, 100))

convert_alpha is function. You missed the parentheses

player_sprite = pygame.image.load("will smith.png").convert_alpha

player_sprite = pygame.image.load("will smith.png").convert_alpha()

Complete example:

import pygame
   
white = (255,255,255)
black = (0,0,0)
orange = (255,165,0) 

pygame.init()
display = pygame.display.set_mode((850,850))
pygame.display.set_caption('Conners Game')

player_sprite = pygame.image.load("will smith.png").convert_alpha()
exit = False
while not exit:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit = True
        print(event)

    display.fill(white)
    display.blit(player_sprite, (100, 100))
    pygame.display.update()

pygame.quit()
quit()

The typical PyGame application loop has to:

  • Related