Skip to content

Commit 36a7d5b

Browse files
committed
Nested menues supported
Sample updated Gititgnore updated
1 parent 45dd9e6 commit 36a7d5b

File tree

3 files changed

+26
-6
lines changed

3 files changed

+26
-6
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -309,3 +309,4 @@ lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/webencodings/labels
309309
lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/webencodings/mklabels.py
310310
lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/webencodings/tests.py
311311
lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/webencodings/x_user_defined.py
312+
consolemenu/__pycache__

console_menu/__init__.py renamed to consolemenu/__init__.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,22 @@ def func3():
1111
print("Im func3")
1212
raise Exception
1313

14+
nested_menu = ConsoleMenu(
15+
"Sample nested menu",
16+
{
17+
"call func1": func1,
18+
"call func2": func2,
19+
"call func3": func3,
20+
}
21+
)
22+
1423
menu = ConsoleMenu(
15-
"This is a test menu",
24+
"Sample menu",
1625
{
1726
"call func1": func1,
1827
"call func2": func2,
1928
"call func3": func3,
29+
"goto nested menu": nested_menu,
2030
}
2131
)
2232
menu.execute()

console_menu/console_menu.py renamed to consolemenu/console_menu.py

+14-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
class ConsoleMenu:
22
"""
33
A simple console menu allows you to easily implement a basic user interface.
4-
You can find a sample below.
4+
You can find a sample in samples.py
55
"""
66
def __init__(self, title, items: dict):
77
"""
@@ -10,6 +10,7 @@ def __init__(self, title, items: dict):
1010
"""
1111
self.items = items
1212
self.title = title
13+
self.__nested = False
1314

1415
def __display(self):
1516
print("\n")
@@ -18,7 +19,7 @@ def __display(self):
1819
for key in self.items:
1920
print(str(i) + ") " + str(key))
2021
i += 1
21-
print(str(i) + ") " + "exit")
22+
print("{}) {}".format(str(i), "back" if self.__nested else "exit"))
2223

2324
def execute(self):
2425
while True:
@@ -30,16 +31,24 @@ def execute(self):
3031
print("Error: Invalid input type")
3132
continue
3233
except KeyboardInterrupt:
33-
exit()
34+
break
3435

3536
if argument not in range(1, len(self.items) + 2):
3637
print("Error: No such item in menu")
3738
continue
3839

3940
if argument == len(self.items) + 1:
40-
exit()
41+
break
4142

4243
try:
43-
list(self.items.values())[argument - 1]()
44+
item = list(self.items.values())[argument - 1]
45+
46+
if isinstance(item, ConsoleMenu):
47+
item.__nested = True
48+
item.execute()
49+
item.__nested = False
50+
else:
51+
item()
52+
4453
except Exception:
4554
print("Error: Failed to run item '{}'".format(list(self.items.keys())[argument - 1]))

0 commit comments

Comments
 (0)