问题描述
我学习了使用 pygame 创建游戏的教程。我刚开始,我已经有问题了。它说它无法找到图像。这是它所说的:
C:\Users\Patryk\AppData\Local\Programs\Python\python39\python.exe:
can't open file ''
C:\Users\Patryk\PycharmProjects\PePeSza-Game\main.py: [Errno 2]
我试图寻找有同样问题的人,但找不到我的问题的答案。完整代码如下:
import pygame
pygame.init()
# Game window
screen_width = 800
screen_height = 640
lower_margin = 100
side_margin = 300
screen = pygame.display.set_mode((screen_width,screen_height))
screen = pygame.display.set_caption(('Level editor'))
# Importing images
bg_img = pygame.image.load('./bg.png')
# Create function for drawing background
def draw_bg():
screen.blit('bg_img',(0,0))
# Mainloop
run = True
while run:
draw_bg()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.update()
pygame.quit()
解决方法
你需要在代码中做两件事
- 删除图像名称前的 ./。它可能会导致问题
# Importing images
bg_img = pygame.image.load('bg.png') # removing the ./
- 在 draw_bg 中的 screen.blit 中,您正在传递字符串,但您需要传递使用 pygame.image.load 制作的对象
# Create function for drawing background
def draw_bg():
screen.blit(bg_img,(0,0)) # removing the apostrophe
完整代码:
import pygame
pygame.init()
# Game window
screen_width = 800
screen_height = 640
lower_margin = 100
side_margin = 300
screen = pygame.display.set_mode((screen_width,screen_height))
screen = pygame.display.set_caption(('Level editor'))
# Importing images
bg_img = pygame.image.load('bg.png')
# Create function for drawing background
def draw_bg():
screen.blit(bg_img,0))
# Mainloop
run = True
while run:
draw_bg()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.update()
pygame.quit()