gpt4 book ai didi

python 2.6 : "Couldn' t open image"error

转载 作者:行者123 更新时间:2023-11-28 19:49:59 25 4
gpt4 key购买 nike

我正在尝试为将要用于游戏的 map 制作基础,但我无法将图像加载到屏幕上。我试过用相同的字母大小写发送图像的绝对文件路径,我试过更改图像的名称,我试过加载在我制作的其他程序中工作的不同图像,我试过把图像与脚本本身位于同一目录中。还没有任何效果。我查看了一些遇到同样问题的人的帖子,例如 Why are my pygame images not loading?我找不到我的问题的答案。图像将不会加载。这是代码:

import sys, pygame
from pygame.locals import *

pygame.init()
size = (600, 400)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Practice Map")
walls = pygame.image.load("C:\Users\dylan\Desktop\Practice Game\brick.jpg")

x = 0
y = 0

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == KEYDOWN and event.key == K_ESCAPE:
sys.exit()
if event.type == KEYDOWN and event.key == K_UP:
y -= 20
if event.type == KEYDOWN and event.key == K_DOWN:
y += 20
if event.type == KEYDOWN and event.key == K_LEFT:
x -= 20
if event.type == KEYDOWN and event.key == K_RIGHT:
x += 20
screen.fill((0,0,0))
screen.blit(walls,(x, 330))
# more bricks to go here later
pygame.display.flip()

#end

和错误:

Traceback (most recent call last):
File "C:\Users\dylan\Desktop\Practice Game\move.py", line 8, in <module>
walls = pygame.image.load("C:\Users\dylan\Desktop\Practice Game\brick.jpg")
error: Couldn't open C:\Users\dylan\Desktop\Practice Gamerick.jpg

我将 Python 2.6 与 PyGame 1.9 一起用于 Python 2.6 版,并将 IDLE 作为我的编辑器。

最佳答案

这里的问题是您使用\作为路径名分隔符,但\也用作 Python 字符串中的转义字符。特别是,\b 表示“退格”(或 '\x08')。由于未知转义序列(如 \X)被视为反斜杠后跟 X 的行为虽然没有完全记录但可靠的行为,但您可以摆脱其他反斜杠。

三种解决方案:

  1. 使用原始字符串,这意味着忽略 Python 字符串转义:r"C:\Users\dylan\Desktop\Practice Game\brick.jpg"
  2. 转义反斜杠:"C:\\Users\\dylan\\Desktop\\Practice Game\\brick.jpg"
  3. 改用正斜杠:"C:/Users/dylan/Desktop/Practice Game/brick.jpg"

如果您已经记住了 Python 转义序列列表,并且愿意依赖可能会改变但可能不会改变的功能,那么您只需在此处转义 \b 即可,但应该清楚为什么其他三个从长远来看是更好的想法。

虽然 Windows 路径名 native 使用反斜杠分隔符,但所有内置和标准库 Python 函数以及第三方库中的大多数函数都非常乐意让您使用正斜杠代替。 (这是有效的,因为 Windows 根本不允许在路径中使用正斜杠。)

要了解其工作原理和原因,您可能想尝试打印出字符串:

>>> print "C:\Users\dylan\Desktop\Practice Game\brick.jpg"
C:\Users\dylan\Desktop\Practice Gamrick.jpg
>>> print r"C:\Users\dylan\Desktop\Practice Game\brick.jpg"
C:\Users\dylan\Desktop\Practice Game\brick.jpg
>>> print "C:\\Users\\dylan\\Desktop\\Practice Game\\brick.jpg"
C:\Users\dylan\Desktop\Practice Game\brick.jpg
>>> print "C:/Users/dylan/Desktop/Practice Game/brick.jpg"
C:/Users/dylan/Desktop/Practice Game/brick.jpg

关于 python 2.6 : "Couldn' t open image"error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14718969/

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