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
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.
/
slash instead of backslash\\
r
or R
precedes double-quotation of a string such as r"..."
\\
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.
© 2024 OneMinuteCode. All rights reserved.