Python,pygame.image.load()函数问题

2024-09-28 03:22:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我跟随了一个turtorial,在那里我正在使用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()

Tags: runmargineventgameimgfordisplaywidth
1条回答
网友
1楼 · 发布于 2024-09-28 03:22:59

在代码中需要做两件事

  1. 删除图像名称前的./before。这可能会引起一些问题
# Importing images
bg_img = pygame.image.load('bg.png') # removing the ./
  1. 在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, 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()

相关问题 更多 >

    热门问题