python - 找到要使用的图像?

标签 python image pygame

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

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

代码将打开“ball.bmp”,但是如何制作像代码一样简单的知道 ball.bmp 位置的东西呢?我在一些临时示例中看到它有效,但我只是不知道它如何找到图像,也不知道如何重新创建它。

最佳答案

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

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

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 的字符串可以使用的任何地方使用,并且还要处理与文件系统上层相关的一些边缘情况/小写标准化, 符号链接(symbolic link),Windows 中用作目录分隔符的“\”也是转义序列中使用的字符,等等)。

最后 - 在较大的项目中,您可以使用此技术来设置指向 Assets 目录的项目范围变量。在项目的 __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")

关于python - 找到要使用的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49185370/

相关文章:

python - 尝试为星球大战机器人创建一个热图,显示哪支军队最具影响力

python Pandas 。如何将特定行的提取结果更新到原特定行的其他列?

Python:递归

python - 当我在终端输入 "python3"时系统会选择哪个 Python3 版本

image - 如何通过 SSIM 确定图像质量?

image - 定向梯度旋转和变换的直方图

python - 通过 PyYAML 序列化命名元组

html - 如何使盒子内的图像响应式 CSS

python-3.x - pygame:pygame.KEYDOWN 不工作

python - 使用 python 渲染并保存视频文件