我正在尝试在Python中的模块之间导航,但我无法返回主菜单。
这是拱门:main.py
来电opa.py
和opb.py
main.py:
import sys, opa, opb
def menu():
print '1. Go opA'
print '2. Go opB'
print '3. Exit'
pick = raw_input('Pick one: ')
if pick == '1':
opa.menu()
elif pick == '2':
opb.menu()
else:
sys.exit()
menu()
opa.py:
def menu():
print '1. Speak'
print '2. Return'
pick = raw_input('Pick one: ')
if pick == '1':
print 'OpA'
elif pick == '2':
main.menu()
opb.py:
def menu():
print '1. Speak'
print '2. Return'
pick = raw_input('Pick one: ')
if pick == '1':
print 'OpB'
elif pick == '2':
main.menu()
当我在opa.py
和opb.py
中选择2时,程序会出现此错误[在这种情况下我会进入opa.py并选择“2. Return”]:
Traceback (most recent call last):
File "main.py", line 16, in <module>
menu()
File "main.py", line 10, in menu
opa.menu()
File "opa.py", line 8, in menu
main.menu()
NameError: global name 'main' is not defined
如果我添加from main import menu
,我会得到另一个:
Traceback (most recent call last):
File "main.py", line 1, in <module>
import sys, opa, opb
File "opa.py", line 1, in <module>
from main import menu
File "main.py", line 16, in <module>
menu()
File "main.py", line 10, in menu
opa.menu()
AttributeError: 'module' object has no attribute 'menu'
我在加载opa.py或opb.py
之前得到它有什么建议吗?
解: 拱门是错误的,所以我在进口后放入了进口。像那样:
def menu():
print '1. Go opA'
print '2. Go opB'
print '3. Exit'
pick = raw_input('Pick one: ')
if pick == '1':
import opa
opa.menu()
elif pick == '2':
import opb
opb.menu()
else:
import sys
sys.exit()
menu()
答案 0 :(得分:1)
“程序中断”有点不清楚,但很可能你忘了添加主菜单的导入():
在您的其他文件之上插入import main
,它应该可以解决问题。