Viết một class menu hiển thị trên console Gồm 1. 1.1 1.2 2. 2.1 2.2 Khi nhập vào 2 Sẽ…
- User
Viết một class menu hiển thị trên console Gồm
- 1.1 1.2
- 2.1 2.2 Khi nhập vào 2 Sẽ hiển thị 2.1 2.2 Khi gõ vào 2 lẫn nữa Sẽ ẩn hiển thị 2.1 2.2 Nếu 2.1 2.2 đang hiển thị thì có thể chọn được
- Assistant
To fulfill your request, we'll create a console-based menu system using Python. This menu will display items and sub-items, and allow the user to expand or collapse sub-menus by entering the corresponding menu numbers. When sub-menus are displayed, users can select them.
Here's the code that implements the described functionality:
class MenuItem: def __init__(self, identifier, name): self.identifier = identifier # e.g., '1', '2', '2.1' self.name = name # Name of the menu item self.sub_items = [] # List of sub-menu items self.expanded = False # Whether the sub-items are expanded def add_subitem(self, item): self.sub_items.append(item) def toggle_expanded(self): self.expanded = not self.expanded def is_leaf(self): return len(self.sub_items) == 0 def find_item(self, identifier): """Recursively find a menu item by its identifier.""" if self.identifier == identifier: return self for sub_item in self.sub_items: result = sub_item.find_item(identifier) if result: return result return None class Menu: def __init__(self): self.items = [] def add_item(self, item): self.items.append(item) def display(self): """Display the menu items.""" for item in self.items: self.display_item(item) def display_item(self, item, indent=0): """Recursively display a menu item and its sub-items.""" print(' ' * indent + f"{item.identifier}. {item.name}") if item.expanded: for sub_item in item.sub_items: self.display_item(sub_item, indent + 1) def run(self): """Run the menu interaction loop.""" while True: self.display() user_input = input("Please select a menu item (or 'exit' to quit): ").strip() if user_input.lower() == 'exit': print("Exiting the menu.") break # Find the menu item corresponding to the user input item = self.find_item(user_input) if item: if not item.is_leaf(): # Toggle expanded state for non-leaf items item.toggle_expanded() else: # Handle selection of leaf items print(f"You have selected {item.identifier}. {item.name}") # You can add code here to perform actions based on the selection else: print("Invalid selection. Please try again.") def find_item(self, identifier): """Find a menu item by its identifier.""" for item in self.items: result = item.find_item(identifier) if result: return result return None # Constructing the menu as per your requirements def build_menu(): menu = Menu() # Main menu items item1 = MenuItem('1', 'Item 1') item1_1 = MenuItem('1.1', 'Sub-item 1.1') item1_2 = MenuItem('1.2', 'Sub-item 1.2') item1.add_subitem(item1_1) item1.add_subitem(item1_2) item2 = MenuItem('2', 'Item 2') item2_1 = MenuItem('2.1', 'Sub-item 2.1') item2_2 = MenuItem('2.2', 'Sub-item 2.2') item2.add_subitem(item2_1) item2.add_subitem(item2_2) menu.add_item(item1) menu.add_item(item2) return menu # Main execution if __name__ == "__main__": menu = build_menu() menu.run()Explanation:
-
MenuItem Class: Represents each menu item. It has an identifier (like '1' or '2.1'), a name, a list of sub-items, and an expanded state to track whether its sub-menu is visible.
-
Menu Class: Represents the whole menu system. It contains methods to display the menu, run the interaction loop, and find items by their identifiers.
-
Building the Menu: The
build_menufunction constructs the menu structure as per your requirements, with main items '1' and '2', each having sub-items '1.1', '1.2', '2.1', and '2.2'. -
Running the Menu: In the
runmethod of theMenuclass, we have an infinite loop that displays the menu, gets user input, and processes it:- If the user inputs 'exit', the program exits.
- If the input corresponds to a menu item:
- If the item is a non-leaf (has sub-items), its expanded state is toggled (expanded or collapsed).
- If the item is a leaf (no sub-items), a selection message is displayed, and any desired action can be performed there.
- If the input doesn't correspond to any menu item, an error message is displayed.
-
User Interaction:
- Initially, only '1. Item 1' and '2. Item 2' are displayed.
- When the user inputs '2', it toggles the expansion of 'Item 2', displaying its sub-items '2.1. Sub-item 2.1' and '2.2. Sub-item 2.2'.
- If '2' is entered again, it collapses 'Item 2', hiding its sub-items.
- When '2.1' or '2.2' are visible, the user can input '2.1' or '2.2' to select those sub-items.
Sample Run:
1. Item 1 2. Item 2 Please select a menu item (or 'exit' to quit): 2 1. Item 1 2. Item 2 2.1. Sub-item 2.1 2.2. Sub-item 2.2 Please select a menu item (or 'exit' to quit): 2.1 You have selected 2.1. Sub-item 2.1 1. Item 1 2. Item 2 2.1. Sub-item 2.1 2.2. Sub-item 2.2 Please select a menu item (or 'exit' to quit): 2 1. Item 1 2. Item 2 Please select a menu item (or 'exit' to quit): exit Exiting the menu.Notes:
- You can expand this code by adding more menu items or implementing actions when leaf items are selected.
- This code uses recursion to display items and find items by identifier, which allows for any depth of sub-menus.
Feel free to run this code and modify it according to your specific needs.
-