How do I get my image in python to appear?

Viewed 45

I have code that moves my beach ball image 1 with wrapping around the edges. When I run the code, I do not get any errors but a blank black screen appears without the ball. When I exit out of the program, the image of the ball appears for a second before closing the program.

import pygame, sys
pygame.init()
screen=pygame.display.set_mode([640,640])
screen.fill([0, 0, 0])
my_ball = pygame.image.load("ball.png")
x=0
y=0
x_speed=5
running=True
while running:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
    pygame.time.delay(20)
    pygame.draw.rect(screen, [0,0,0], [x, y, 0, 0], 0)
    x=x+x_speed
if x>screen.get_width():
    x=0
screen.blit(my_ball,[x, y])
pygame.display.flip()
pygame.quit()
2 Answers

You should put

screen.blit(my_ball,[x, y])
pygame.display.flip()

inside the while loop like this:

while running:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
    pygame.time.delay(20)
    pygame.draw.rect(screen, [0,0,0], [x, y, 0, 0], 0)
    x=x+x_speed
    screen.blit(my_ball,[x, y])
    if x>screen.get_width():
        x=0

    pygame.display.flip()

and probably the if statement as well

also instead of

pygame.draw.rect(screen, [0,0,0], [x, y, 0, 0], 0)

you can simply use

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

which just fills the screen with specified color

The screen is staying black because the drawing operations are never flushed to the display.

Your code has a simple indentation bug, everything from if x>screen... to pygame.display.flip() (inclusive) should be part of the while running loop.

e.g.:

while running:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
    #pygame.time.delay(20)    # don't delay the main loop, use clock.tick()

    pygame.draw.rect(screen, [0,0,0], [x, y, 0, 0], 0)

    x=x+x_speed
    if x>screen.get_width():
        x=0
    screen.blit(my_ball,[x, y])
    pygame.display.flip()

pygame.quit()
Related