如何修复风中Python Pygame图像错误

2024-09-29 21:33:33 发布

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

我试图通过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 (most recent call last):

File "C:/Users/Dawn/PycharmProjects/snakegame/snake.py", line 13, in carImage = pygame.image.load('you.png')

pygame.error: Couldn't open you.png

请帮帮我,我不知道为什么会这样。你知道吗

我现在使用的是window10,我使用了C: \.\...\you.png方法 但还是不行。你知道吗


Tags: imageimportyoueventpngdisplaywidthpygame
1条回答
网友
1楼 · 发布于 2024-09-29 21:33:33

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

问题似乎是它,因为下面的代码对我来说工作得很好。我们认为您有一个images\u 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-查看有关的更多信息操作系统路径here。你知道吗

我用的是MacOS。你知道吗

相关问题 更多 >

    热门问题