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
error Traceback (most recent call last)
<ipython-input-17-cdbff3e182ab>in<module>
34 sys.exit()
35
--- >36 main()
37
<ipython-input-17-cdbff3e182ab>in main()
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\pygame\bg.png
The error message appears, and the bg.png cannot be read.
Verified that the image file is in the same file as the program.How can I improve it?
If you have a file, but you'd rather rewrite it to one of the following than suffer from the appearance of a file path because you interpret the backslash character as an escape sequence.
Directory delimiter to slash characters (Unix Style Path)
pygame.image.load("c:/prog/python/pygame/bg.png")
RAW String
pygame.image.load(R"c:\prog\python\pygame\bg.png")
Create a path with os.path.join
pygame.image.load(os.path.join("c:", "prog", "python", "pygame", "bg.png")
US>Unix Style Path
Directory delimiter as slash character
pygame.image.load("c:/prog/python/pygame/bg.png")
RAW string
pygame.image.load(R"c:\prog\python\pygame\bg.png")
Create a Path with os.path.join
pygame.image.load(os.path.join("c:", "prog", "python", "pygame", "bg.png")
If you still can't read it, the png
file is not supported as described in https://www.pygame.org/docs/ref/image.html#pygame.image.load.
© 2024 OneMinuteCode. All rights reserved.