找到要使用的图片?

时间:2018-03-09 01:43:39

标签: python image pygame

我是Python的新手,我从来没有学过这一件事:如何在没有长行代码的情况下找到一个平移工作目录或设置目录的图像?这是一个例子。

screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.bmp")
ballrect = ball.get_rect()

代码会打开“ball.bmp”,但是如何创建一个知道ball.bmp在哪里的东西就像那段代码一样简单?我已经在一些临时示例中看到了它,但我不知道它是如何找到图像的,也不知道如何重新创建它。

1 个答案:

答案 0 :(得分:1)

对于“非玩具”应用程序,Python代码中使用了一种模式来查找与当前运行文件相关的资产。

Python模块在运行时具有__file__变量 - 指向包含当前模块的文件。因此,如果您从__file__获取目录,则可以拥有资产的绝对路径:

import os
here = os.path.abspath(os.path.dirname(__file__))

image_file = os.path.join(here, "ball.png") # Please don't use bmp  :-) 

此外,如果您使用的是Python 3.6及更高版本,则可以使用pathlib.Path代替长度os.path来电:

from pathlib import Path
import os

here = Path(os.path.dirname(__file__))

image_file = here / "ball.png"

Path覆盖“/”运算符,以便它产生“路径对象” - 这些可以使用任何包含Path can的字符串,另外还要处理与文件系统大小写相关的一些边缘情况正常化, 符号链接,在Windows中用作目录分隔符的'\'也是转义序列中使用的字符等等。

最后 - 在更大的项目中,您可以使用此技术设置指向资产目录的项目范围变量。在项目的__init__文件中,您可以执行以下操作:

from pathlib import Path
import os

here = Path(os.path.dirname(__file__))

asset_dir = here / "assets"
image_dir = asset_dir / "images"
sound_dir = asset_dir / "sounds"

...
# and, in other file: 
from projectname import image_dir
...
def myfunc(...):
     ...
     image = pygame.image.load(image_dir / "spritename.png")