Unable to load pygame image

Asked 3 months ago, Updated 3 months ago, 8 views

import pygame
from pygame.locals import*
import sys

defmain():
    (w,h) = (400,400)
    (x,y) = (200,200)
    pygame.init()
    screen=pygame.display.set_mode(w,h), 0,32)
    screen=pygame.display.get_surface()
    pygame.display.set_caption("Pygame Test")

    bg = pygame.image.load("C:\prog\python\pygame\bg.png").convert_alpha
    rect_bg = bg.get_rect()

    player=pygame.image.load("C:\prog\python\pygame\player.png").convert_alpha
    rect_player=player.get_rect()
    rect_player.center=(x,y)

    while(1):
        pygame.display.update()
        pygame.time.wait(30)
        screen.fill(0,20,0,0))
        screen.blit(bg, rect_bg)
        screen.blit(player, rect_player)

        for event in pygame.event.get():
            if event.type==QUIT:
                pygame.quit()
                sys.exit()
            if event.type==KEYDOWN:
                if event.key==K_ESCAPE:
                    pygame.quit()
                    sys.exit()

main()

Enter

11 pygame.display.set_caption("Pygame Test")
     12 
--- >13bg = pygame.image.load("C:\prog\python\pygame\bg.png").convert_alpha
     14 rect_bg = bg.get_rect()
     15 

error:Couldn't open C:\prog\python\pygamg.png

The error bg.png failed to open.Why can't I open the image file when it is in the same location as the file containing this code?

python image

2022-09-30 14:28

1 Answers

The reason may be that the path is separated by only one backslash \ and the first character in the filename is \b to create a backspace escape sequence.

The error message is error:Couldn't open C:\prog\python\pygamg.png and the e\b has been removed from the source filename "C:\prog\python\pygame\bg.png" by the backspace (deleted last character).
\p is not an escape sequence, so it is left as it is.

There is a string literal specification that includes escape sequences.
2.4.1.String and Byte String Literal

The countermeasures are one of the following.

  • change path delimitation to / slash instead of backslash
  • If you want to leave it at the backslash, one of the following:
    • Continuous backslashes and two
    • such as \\
    • r or R precedes double-quotation of a string such as
    • r"..."
  • Continuous backslashes and two
  • such as \\
  • r or R precedes double-quotation of a string such as
  • r"..."

There is also a way to make only two backslashes before characters that become escape sequences, but it is complicated because you have to remember what you want and consider every time you write a path.


2022-09-30 14:28

If you have any answers or tips


© 2023 OneMinuteCode. All rights reserved.