Python添加png图片出现的问题和解决

在使用Python的pygame库加载PNG图片时,如果只提供文件名而不包含完整路径,会出现'pygame.error: Couldn’t open 图片名.png'的错误。解决方法是在路径前添加'r',或者提供完整的绝对路径,例如:r"C:/_____/caixukun.png"。确保正确指定图片文件的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python添加png图片出现的问题

#加载一个png图片
import pygame,sys
pygame.init()
screen=pygame.display.set_mode([640,480])
screen.fill([255,255,255])

my_ball=pygame.image.load(“caixukun.png”)

my_ball=pygame.image.load(“C:/______/caixukun.png”)

my_ball=pygame.image.load(r"caixukun.png")

my_ball=pygame.image.load(r"C:/_____/caixukun.png")

screen.blit(my_ball,[50,50])
pygame.display.flip()
running=True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
pygame.quit()

有四种添加png的代码

名称.png

路径/名称.png

r名称.png

r路径/名称.png

______下划线为png路径

单独只有名称的方法会显示以下:
PS D:\PythonDate> python 16-20.py
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File “16-20.py”, line 102, in
my_ball=pygame.image.load(“caixukun.png”)
pygame.error: Couldn’t open caixukun.png
错误名称,无法打开caixukun.png

必须添加路径名称

添加路径名称之后的运行结果:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值