【问题标题】:How to fix Python Pygame image error in window如何修复窗口中的 Python Pygame 图像错误
【发布时间】:2018-11-14 03:14:50
【问题描述】:

我试图通过 pygame 将 png 文件加载到 python,但它不起作用 这是我的代码:

import pygame
from pygame.locals import *
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Game")
clock = pygame.time.Clock()
carImage = pygame.image.load('you.png')
def car(x,y):
    gameDisplay.blit(carImage,(x,y))
    x = (display_width * 0.45)
    y = (display_height * 0.8)
    crashed = False
    while not crashed:
       for event in pygame.event.get():
           if event.type == pygame.QUIT:
               crashed = True
       gameDisplay.fill(white)
       car(x,y)
       pygame.display.update()
       clock.tick(24)
    pygame.quit()
    quit()

它说:

Traceback(最近一次调用最后一次):

文件“C:/Users/Dawn/PycharmProjects/snakegame/snake.py”,第 13 行,在 carImage = pygame.image.load('you.png')

pygame.error: 无法打开你.png

请帮帮我,我不知道为什么会一直显示。

我现在使用的是窗口 10,我使用了 C: \.\...\you.png 方法 但还是不行。

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    基于this answer,建议使用相对路径。这样做总是更好,因为您不必关心“\”、“/”或操作系统(有人已经为我们做了:v)。

    问题似乎是它,因为下面的代码对我来说效果很好。我们认为您有一个 images_store 文件夹来将您的图像存储在与 .py 文件相同的父目录中(当然,您可以随意更改它)。

    import pygame
    import os.path as osp
    from pygame.locals import *
    
    
    pygame.init()
    
    display_width, display_height = 800, 600
    black = (0,0,0)
    white = (255,255,255)
    red = (255,0,0)
    
    current_path = osp.dirname(__file__)                          # Where your .py file is located
    image_path = osp.join(current_path, 'images_store')           # The image folder path
    carImage = pygame.image.load(osp.join(image_path, 'you.png'))
    
    
    gameDisplay = pygame.display.set_mode((display_width, display_height))
    pygame.display.set_caption("Game")
    clock = pygame.time.Clock()
    
    def car(x,y):
       gameDisplay.blit(carImage, (x, y))
    
    x = (display_width * 0.45)
    y = (display_height * 0.8)
    crashed = False
    while not crashed:
       for event in pygame.event.get():
           if event.type == pygame.QUIT:
               crashed = True
       gameDisplay.fill(white)
       car(x,y)
       pygame.display.update()
       clock.tick(24)
    pygame.quit()
    quit()
    

    p.s.1 - 查看更多关于 os.path 的信息here

    p.s.2 - 我使用的是 MacOS。

    【讨论】:

      猜你喜欢
      • 2021-06-05
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 2018-01-28
      相关资源
      最近更新 更多