[英]I am unable to import a file no matter what I do
盡管這被問了上百萬次,但這個案例很特別,因為要么我很笨,要么我的筆記本電腦很笨。 所以為了確保每個人都在同一個頁面上,這就是我想要做的:在fish life imulator.py
中使用import menu
,這是我所做的文件樹:
fish_life_simulator
fish_life_simulator.py
extra_programs
__init__.py
menu.py
我嘗試了所有我發現的東西, os.chdir
重定向到額外的程序文件夾, sys.path.append
或sys.path.insert
, import file
or from file import def
, __init__.py
如你所見,但我似乎總是得到同樣的錯誤: ModuleNotFoundError: No module named 'menu'
編輯:這是我的代碼示例: fish_life_simulator
import pygame, random, time, sys, os
from pygame.locals import *
os.chdir(os.path.dirname(__file__))
pygame.init()
size_of_monitor = pygame.display.Info()
flags = RESIZABLE
width = size_of_monitor.current_w - 25
height = size_of_monitor.current_h - 50
from extra_programs import menu
screen, screen_size, menu_background_image, menu_background_stretched_image, menu_background_rect = initiation(width, height, flags)
menu.py
def initiation(width, height, flags):
screen = pygame.display.set_mode((width, height), flags)
screen_size = screen.get_size()
menu_background_image = pygame.image.load(r'sprites\menu_background.jpg')
menu_background_stretched_image = pygame.transform.scale(menu_background_image, (screen_size))
menu_background_rect = menu_background_stretched_image.get_rect()
return screen, screen_size, menu_background_image, menu_background_stretched_image, menu_background_rectscreen, screen_size, menu_background_image, menu_background_stretched_image, menu_background_rect
在文件夾fish_life_simulator
執行
PYTHONPATH=. python fish_life_simulator.py
您的導入在fish_life_simulator.py
中的位置
from extra_programs import menu
...
或文件夾fish_life_simulator
外的一級執行
PYTHONPATH=fish_life_simulator/ python fish_life_simulator/fish_life_simulator.py
您的導入在fish_life_simulator.py
中的位置
from fish_life_simulator.extra_programs import menu
...
我讓它使用以下文件夾結構和以下代碼:
fish_life_simulator
|-- extra_programs
| |-- __init__.py
| `-- menu.py
`-- fish_life_simulator.py
菜單.py
def menu():
print("hello from menu")
fish_life_simulator.py
from extra_programs import menu
menu.menu()
根本不需要編輯路徑或類似的東西。
只需導航到文件夾fish_life_simulator
並使用python fish_life_simulator.py
運行代碼。
如果您不想鍵入menu.
前綴,您可以像下面這樣調整fish_life_simulator.py
:
from extra_programs.menu import menu
menu()
在您的代碼中,您缺少前綴,在調用initiation(...)
時,它應該是menu.initiation(...)
。 您需要選擇上述其中一種導入方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.