🌐
Reddit
reddit.com › r/python › menus in python
r/Python on Reddit: Menus in Python
May 25, 2022 -

Hi there folks,

I suddenly realized in the design of a Python script that the best would be to allow my users to make selections using menus. You got the idea: you are given a menu, you select an option and thus, another menu is shown and so forth until a terminal selection is made and the python script performs the associated action. I'm not interested in graphical menus but just plain text/ascii menus.

It impressed me quite a lot that I did not found any specific package for this. Do you guys have any recommendation?

Thanks a lot!

🌐
GitHub
github.com › aegirhall › console-menu
GitHub - aegirhall/console-menu: A simple Python menu system for building terminal user interfaces. · GitHub
A simple Python menu system for building terminal user interfaces. - aegirhall/console-menu
Starred by 375 users
Forked by 61 users
Languages   Python
Discussions

using Python Menu package? - Stack Overflow
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. Putting the following line in the __init__.py file of the menu ... More on stackoverflow.com
🌐 stackoverflow.com
python - CLI Menu library - Code Review Stack Exchange
I started writing a small CLI menu library in python. I'm uncertain of the structure and scalability of the current code. For example the Menu.choice method would grow very large if were to add more More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
August 4, 2019
command line interface - Python CLI Menu with Arrow Keys on Windows - Stack Overflow
The terminal I use on Windows is Mingw-w64 (Git Bash). I am trying to find or create a CLI menu with Python that I can navigate with arrow keys, however nothing I find works. The Python library, si... More on stackoverflow.com
🌐 stackoverflow.com
Creating a Menu in Python - Stack Overflow
I'm working on making a menu in python that needs to: Print out a menu with numbered options Let the user enter a numbered option Depending on the option number the user picks, run a function spec... More on stackoverflow.com
🌐 stackoverflow.com
🌐
PyPI
pypi.org › project › console-menu
console-menu · PyPI
Menu items can now be selected using letters rather than numbers; however, the Enter key is still required for input to be accepted. Added support for Python 3.10 and 3.11. Dropped support for Python 3.6. Partial fix for ansiwrap import when using PyInstaller (issue #66). The issue is caused by the ansiwrap library ...
      » pip install console-menu
    
Published   Mar 05, 2023
Version   0.8.0
🌐
PyPI
pypi.org › project › Menu
Menu · PyPI
Easily create command-line menus. ... Note: Use with Python 2 requires the future package to be installed.
      » pip install Menu
    
Published   Jun 07, 2019
Version   3.2.2
🌐
GitHub
github.com › pmbarrett314 › curses-menu
GitHub - pmbarrett314/curses-menu: A simple console menu system in python using the curses library · GitHub
Windows users can visit http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses and get a third-party build for your platform and Python version. ... It’s designed to be pretty simple to use. Here’s an example · menu = CursesMenu("Root Menu", "Root Menu Subtitle") item1 = MenuItem("Basic item that does nothing", menu) function_item = FunctionItem("FunctionItem, get input", input, ["Enter an input: "]) print(__file__) command_item = CommandItem( "CommandItem that opens another menu", f"python {__file__}", ) submenu = CursesMenu.make_selection_menu([f"item{x}" for x in range(1, 20)]) submenu_item
Starred by 477 users
Forked by 49 users
Languages   Python
🌐
PyPI
pypi.org › project › Menu › 1.4
Menu 1.4
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Stack Overflow
stackoverflow.com › questions › 33513595 › using-python-menu-package
using Python Menu package? - Stack Overflow
I have tried installing the following python package: https://pypi.python.org/pypi/Menu/1.4 on both OSX(El Capitan) and Linux Mint. Using the examples given on the website to install and use this
🌐
Mikusa
mikusa.com › projects › menuSystem
Python Menu System - Daniel Mikusa
Here’s a link to download the most recent version of this library. Download Now. ... In case you are wondering “What does this package do?”, wonder no more. It creates simple menuing systems.
Find elsewhere
🌐
PyPI
pypi.org › project › pymenu-console
pymenu-console · PyPI
pymenu is a python library for creating interactive, console-based menus.
      » pip install pymenu-console
    
Published   Mar 04, 2024
Version   0.2.1
🌐
GitHub
github.com › topics › python-menu
python-menu · GitHub Topics · GitHub
Ideal for people who want to quickly make a menu without writing their own complicated crutches. Includes: SelectorMenu, MultipleSelectorMenu, FunctionalMenu. python library pip menu console-application curses-library console-library menusystem console-menu python-menu
🌐
Medium
medium.com › @anushkasnawale › python-menu-based-program-370f7129f032
Python Menu-Based Program. Python Menu-based program allows the… | by Anushka Nawale | Medium
September 14, 2023 - Python Menu-based program allows the user to perform various tasks, including listing files in the current directory, web scraping from a URL, plotting a sample chart, and exiting the program.
Top answer
1 of 1
1
  • Docstrings: You should include a docstring at the beginning of every method/class/module you write. This will help any documentation identify what your code is supposed to do.
  • Naming: Python variables and parameters should be in snake_case, not camelCase.
  • len as condition: You shouldn't use if len(self.title):, instead you should check if it doesn't exist, if not self.title, as it is more compliant with PEP-8. This StackOverflow answer provides more insight.
  • String formatting: This one is a personal preference. I like to use f"" to format my strings because it allows me to directly include variables into the string, without having to chain a .format() onto the end. Again, this is purely personal, but see how you like it.
  • Imports: Another personal preference, I like to organize my imports alphabetically so it's more organized. This is all up to you if you want to keep with this practice, but do make sure to follow PEP-8 Import Guide to make sure you're following standard and accepted practies.
  • Unnecessary methods: show_title and show_header is basically extra and unneeded code. You're essentially redefining the print method. Just print the title/header whenever you need to, instead of calling these methods.

Updated Code

import os
import sys

class Menu:
    """ Menu class for displaying and adding to menu """
    def __init__(self, *items, **kwargs):
        self.items = []
        self.title = kwargs.get('title', '')
        self.header = kwargs.get('header', '')
        for item in items:
            self.add(item)

    def add(self, *items):
        """ Adds each element in `list` to items """
        for item in items:
            self.items.append(item)
            if hasattr(item, 'sub_menu'):
                self.add_parent_to_child(item.sub_menu)

    def show(self):
        """ Displays the items and calls method to collect user input """
        clear()
        if self.header:
            print(self.header)
        if self.title:
            print(self.title)
        for i, item in enumerate(self.items):
            print(f"[{i + 1}] {item.title}")
        self.choice()

    def choice(self):
        """ Collects user input """
        while 1:
            try:
                choice = input('> ')
                if choice == 'q':
                    clear()
                    sys.exit()
                if choice == 'b':
                    if hasattr(self, 'parent'):
                        self.show()
                    else:
                        self.show()
                        continue
                if not choice.isdigit():
                    raise ValueError
                item = self.items[int(choice) - 1]
                if hasattr(item, 'callback'):
                    item.callback()
                if hasattr(item, 'sub_menu'):
                    item.sub_menu.show()
                if not hasattr(item, 'sub_menu') and not hasattr(item, 'callback'):
                    print(f"{item.title} is an empty menu...")
            except (ValueError, IndexError):
                self.show()
                continue

    def add_parent_to_child(self, child):
        """ Adds the passed `child` to the parent of the object """
        child.parent = self


class MenuItem:
    """ Specific class for items in the menu """

    def __init__(self, title, sub_menu=None, callback=None, tag=''):
        self.title = title
        if sub_menu is not None:
            self.sub_menu = sub_menu
            if self.title:
                sub_menu.title = self.title
        if callback is not None:
            self.callback = callback
        if tag:
            self.tag = tag

def clear():
    """ Clears the console screen """
    os.system('cls') if os.name == 'nt' else os.system('clear')

if __name__ == '__main__':
    ITEM_1 = MenuItem('empty test 1')
    ITEM_2 = MenuItem('empty test 2')
    SUBMENU_1 = Menu(ITEM_1, ITEM_2)
    ITEM_3 = MenuItem('sub menu', sub_menu=SUBMENU_1)
    TEST_MENU = Menu(ITEM_1, ITEM_2, ITEM_3, title='Main Menu')
    TEST_MENU.show()
🌐
Libraries.io
libraries.io › pypi › python-cli-menu
python-cli-menu 1.8.1 on PyPI - Libraries.io - security & maintenance data for open source software
python-cli-menu is a simple cross-plateform Python module that allows you to easilly create pretty custom menus in console. Customize the title, options, every colors and initial cursor position as you wish.
🌐
LinkedIn
linkedin.com › pulse › python-menu-program-various-tasks-amit-sharma
Python Menu Program for Various Tasks
August 7, 2023 - Introduction The Python menu program is designed to provide a user-friendly interface to perform a variety of tasks. The program uses the tkinter library for GUI components and integrates multiple Python libraries and APIs for different ...
🌐
Tutorialspoint
tutorialspoint.com › python › tk_menu.htm
Tkinter Menu
from tkinter import * def donothing(): filewin = Toplevel(root) button = Button(filewin, text="Do nothing button") button.pack() root = Tk() menubar = Menu(root) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="New", command=donothing) filemenu.add_command(label="Open", command=donothing) filemenu.add_command(label="Save", command=donothing) filemenu.add_command(label="Save as...", command=donothing) filemenu.add_command(label="Close", command=donothing) filemenu.add_separator() filemenu.add_command(label="Exit", command=root.quit) menubar.add_cascade(label="File", menu=filemenu
Top answer
1 of 3
4

The cutie library might be what you want. Example:

options = [f'Choice {i}' for i in range(1, 5)]
chosen_idx = cutie.select(options)
chosen = options[chosen_idx]
2 of 3
1

In Windows OS (and only for 32 bits Python versions), you can use 'unicurses' module. You can download it from pypi.org (https://pypi.org/project/UniCurses/1.2/) and install it as a .exe file.

when you have already installed it, it will appear an 'import module error', all about it is explained on this post here in SOF just in case: UniCurses pdcurses.dll Error

Basically you have to download 'pdcurses.dll' (here is a link: https://www.opendll.com/index.php?file-download=pdcurses.dll&arch=32bit&version=3.4.0.0) and move it to a specific directory. It's detalled on the post above.

Here is an example code of how this module works to use it with Arrow Keys:

from unicurses import *

WIDTH = 30
HEIGHT = 10
startx = 0
starty = 0

choices = ["Choice 1", "Choice 2", "Choice 3", "Choice 4", "Exit"]
n_choices = len(choices)

highlight = 1
choice = 0
c = 0

def print_menu(menu_win, highlight):
    x = 2
    y = 2
    box(menu_win, 0, 0)
    for i in range(0, n_choices):
        if (highlight == i + 1):
            wattron(menu_win, A_REVERSE)
            mvwaddstr(menu_win, y, x, choices[i])
            wattroff(menu_win, A_REVERSE)
        else:
            mvwaddstr(menu_win, y, x, choices[i])
        y += 1
    wrefresh(menu_win)

stdscr = initscr()
clear()
noecho()
cbreak()
curs_set(0)
startx = int((80 - WIDTH) / 2)
starty = int((24 - HEIGHT) / 2)

menu_win = newwin(HEIGHT, WIDTH, starty, startx)
keypad(menu_win, True)
mvaddstr(0, 0, "Use arrow keys to go up and down, press ENTER to select a choice")
refresh()
print_menu(menu_win, highlight)

while True:
    c = wgetch(menu_win)
    if c == KEY_UP:
        if highlight == 1:
            highlight == n_choices
        else:
            highlight -= 1
    elif c == KEY_DOWN:
        if highlight == n_choices:
            highlight = 1
        else:
            highlight += 1
    elif c == 10:   # ENTER is pressed
        choice = highlight
        mvaddstr(23, 0, str.format("You chose choice {0} with choice string {1}", choice, choices[choice-1]))
        clrtoeol()
        refresh()
    else:
        mvaddstr(22, 0, str.format("Character pressed is = {0}", c))
        clrtoeol()
        refresh()
    print_menu(menu_win, highlight)
    if choice == 5:
        break

refresh()
endwin()

And here is an image of the result on the command line interface (CMD):

🌐
Medium
medium.com › @dghadge2002 › building-a-command-line-menu-in-python-exploring-different-applications-f970a61e6412
Building a Command-Line Menu in Python: Exploring Different Applications | by Dinesh Ghadge | Medium
December 28, 2023 - Introduction: In this blog post, we will walk through the process of creating a simple menu code in Python that allows users to launch…
🌐
GitHub
github.com › afonsocrg › yacli_menu
GitHub - afonsocrg/yacli_menu: A set of utils to make it easier to create interactive menus in python · GitHub
A set of utils to make it easier to create interactive menus in python - afonsocrg/yacli_menu
Author   afonsocrg