aegirhall / console-menu

A simple Python menu system for building terminal user interfaces.
MIT License
365 stars 58 forks source link

How to display returned values on the menu screen? #49

Closed rwgnr closed 4 years ago

rwgnr commented 4 years ago

If I am presenting a console-menu that is listed with a FunctionItem, how do I return and display data from the function that executed, or is that not a built in feature?

Looking at the documentation, get_return on FunctionItems seems to be appropriate for what I'm looking for, but I'm not sure what I'm missing to get it to show at the menu screen.

Does anyone have any thoughts of where that could be added to the below example?

from consolemenu import *
from consolemenu.items import *

def helloWorld():
    value = "Hello World"
    return value

menu = ConsoleMenu("My Menu Name")
function_item1 = FunctionItem("Hello World", helloWorld)
menu.append_item(function_item1)
menu.show()
aegirhall commented 4 years ago

Hi @rwgnr

When your menu item needs to print output to screen, you'll need to halt that input at the end (or periodically with some form of pagination). A simple way to do this would be to add a "Press [Enter] to continue" prompt at the end of your processing using the PromptUtils class, like so:

from consolemenu import ConsoleMenu, Screen
from consolemenu.items import FunctionItem
from consolemenu.prompt_utils import PromptUtils

def print_report():
  screen = Screen()
  try:
    screen.println("\n\nThis is my report.")
  except Exception as e:
    screen.println("Error printing report: %s" % e)
  finally:
    screen.println()
    PromptUtils(screen).enter_to_continue() 

def main():
  menu = ConsoleMenu("My Menu")
  report_menu_item = FunctionItem("Print Report", print_report)
  menu.append_item(report_menu_item)
  menu.show()

if __name__ == "__main__":
  main()

Since not all menu items are necessarily meant to display results to a user, or because results need to be paginated, there currently isn't a feature to allow the screen to "halt". But it seems many people would like this to be a built-in feature so maybe I'll consider adding it as an option.

rwgnr commented 4 years ago

Thanks @aegirhall I appreciate the response on this! I agree, I think that's the best path forward as well.

Keep up the great work and thank you for your effort on this project!