ModuleNotFoundError: 未找到模块名称 states

huangapple go评论73阅读模式
英文:

ModuleNotFoundError: No module name states

问题

这是我的目录结构:

.
└── Test_game
    ├── game_play.py
    ├── game.py
    ├── map
    │   └── map.png
    └── states
        ├── state.py
        └── title.py

当我尝试在 title.py 中导入 State 时:

from states.state import State

我在 game.py 中也遇到了相同的错误:

from states.title import Title

我正在尝试创建多个游戏状态,但不确定哪里出了问题。我还尝试在终端中运行 pip3 install states

英文:

This is my directory structure:

.
└── Test_game
    ├── game_play.py
    ├── game.py
    ├── map
    │   └── map.png
    └── states
        ├── state.py
        └── title.py

When I try to import State into title.py:

from states.state import State

I get the same error in my game.py

from states.title import Title

I'm trying to make multiple game states, but I'm not sure what I'm doing wrong. I also tried to pip3 install states into the terminal.

答案1

得分: 1

以下是翻译好的内容:

似乎您想从同一目录中的另一个文件导入内容。实现您想要的最简单方法是使用相对导入,即不要使用from states.state import State,而只使用from .state import State(不以states开头)。

您面临的问题是,您位于一个文件夹内(顺便说一句:甚至不是一个包,因为找不到__init__.py文件),并且想要向上搜索文件夹路径。显然,没有配置搜索路径以执行此操作。但这没关系,因为要导入的目标模块(位于您要导入的源模块的搜索路径上)始终位于源模块的搜索路径上。因此,您可以简单地利用Python的相对导入功能。

如果您想了解更多信息,可以查看Python关于导入语句的文档,甚至还有关于打包的教程,可能也会对您有所帮助。

英文:

It seems that you want to import from another file in the same directory. The easiest way to achieve what you want is to use relative imports, i.e. don't use from states.state import State, but only use from .state import State (without states at the beginning).

The problem you're facing is that you are inside a folder (btw: even not being a package, because no __init__.py is found) and want to search the folder path up. There is obviously no search path configured that let you do this. But this is okay, because the target module on the same folder (which you want to import) is always on the search path of the source module (where you want to import). So you can simply make use of Python's relative imports abilities.

If you want to read more, here is the Python documentation about the import statement and even further a tutorial about packaging, which could also be of interest.

huangapple
  • 本文由 发表于 2023年5月23日 01:09:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76308499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定