3

Hello I am following the pygame game code and I get the following error and post a question. When I run it, the screen pops up and then disappears immediately.The background color is also executed without saving. (Mac OS)

import pygame

pygame.init() # 초기화 (반드시 필요)

#화면 크기  설정
screen_width = 480 # 가로 크기
screen_height = 640 # 세로 크기
screen = pygame.display.set_mode((screen_width, screen_height))

# 화면 타이틀 설정
pygame.display.set_caption("Kim Game") # 게임 이름

# 배경 이미지 블로오기
background = pygame.image.load(("r'C:/Users/king/Desktop/practica/pygame_basic/background.png"))

# 이벤트 루프 
running = True # 게임이 진행중인가?
while running:
    for event in pygame.event.get(): # 어떤 이벤트가 발생하였는가?
        if event.type == pygame.QUIT: # 창이 닫히는 이벤트가 발생하였는가?
            running = false # 게임이 진행중이 아님

    screen.blit(background, (0, 0)) # 배경 그리기

    pygame.display.update() # 게임화면을 다시 그리기      

# prgame 종료
pygame.quit

Execution FileNotFoundError: No such file or directory.

2 Answers2

3

r must be a prefix, not the content of the string. It has to be r"string" instead of "r'string":

background = pygame.image.load(("r'C:/Users/king/Desktop/practica/pygame_basic/background.png"))

background = pygame.image.load(r"C:/Users/king/Desktop/practica/pygame_basic/background.png")

String with prefix 'r' or 'R' are called raw strings and treat backslashes as literal characters. See String and Bytes literals.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • Even if I change it, it does not run the same. – In Hwan Kim Mar 07 '21 at 14:11
  • @InHwanKim Does the image file exist? Is the file extension correct ("png")? – Rabbid76 Mar 07 '21 at 14:13
  • Yes, the file is in that location. The file type is correct.("png") – In Hwan Kim Mar 07 '21 at 14:38
  • @InHwanKim No it is not. If it were there, you won't get this error. Carefully examine the file path for typos. – Rabbid76 Mar 07 '21 at 14:39
  • No, the real file location is correct and the image file is correct... I don't know why, I want to show the picture in the location... – In Hwan Kim Mar 07 '21 at 15:01
  • 1
    @InHwanKim Sorry, you are wrong. It can't be correct. Don't be stubborn. Copy the file to a different directroy (e.g. `r'c:\background.png'` and try it again. If it works, the original file path is incorrect. – Rabbid76 Mar 07 '21 at 15:04
  • Wow solved it. Code background = pygame.image.load("/Users/king/Desktop/practica/pygame_basic/background.png") I wrote this and it runs normally. Thank you. For help – In Hwan Kim Mar 07 '21 at 15:22
1

this error means that there is a file that does not exists in your game directory you have to add an image called background.png in the pygame_basic folder