Python 2.6:"无法打开图像"错误

Dyl*_*ere 2 python pygame image

我正在尝试为我将要用于游戏的地图制作基础,但我无法将图像加载到屏幕上.我已经尝试使用likeame letter将绝对文件路径发送到图像,我尝试更改图像的名称,我尝试加载在我制作的其他程序中工作的不同图像,并且我已尝试将与脚本本身位于同一目录中的图像.什么都没有奏效.我查看了几个遇到同样问题的人的线程,例如为什么我的pygame图像没有加载?我无法找到问题的答案.图像无法加载.这是代码:

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
Run Code Online (Sandbox Code Playgroud)

和错误:

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
Run Code Online (Sandbox Code Playgroud)

我使用Python 2.6和PyGame 1.9 for Python 2.6版,IDLE作为我的编辑器.

aba*_*ert 5

这里的问题是您使用\作为路径名分隔符,但\也用作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路径名本身使用反斜杠分隔符,但所有内置和标准库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
Run Code Online (Sandbox Code Playgroud)