gpt4 book ai didi

python - 如何修复窗口中的 Python Pygame 图像错误

转载 作者:行者123 更新时间:2023-12-01 08:46:15 25 4
gpt4 key购买 nike

我试图通过 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

请帮助我,我不知道为什么这个一直显示。

我现在使用的是 Windows 10,并且执行了 C:\.\...\you.png 方法但还是不行。

最佳答案

基于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。

关于python - 如何修复窗口中的 Python Pygame 图像错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53292682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com