Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
A simple menu with submenus
-
I thought someone might find this useful. Also, feedback on code style ('the python way of doing things') would be appreciated, I've been coding in Python for less than 12 hours.
It is a way to present a simple menu with submenus, and returns the selections for further processing. The example provided is from a food diary script I'm converting from Workflow that I used to use with Day One.
I know there is no kind of error checking at all, for my purposes I don't really think that's necessary.
Should work in Pythonista too.
import dialogs def menuWithSubmenus(menuTitle, menuList): #Present main menu and get user choice mainMenu = ([d['mainMenuOption'] for d in menuList]) choice = dialogs.list_dialog(title=menuTitle, items=mainMenu, multiple=False) #Present sub-menu and get user choice subMenu = (next((item for item in menuList if item['mainMenuOption'] == choice))['subMenuOptions']) subChoice = dialogs.list_dialog(title=menuTitle, items=subMenu, multiple=False) return { 'mainMenuOption':choice, 'subMenuOption': subChoice } #Example Usage menuItems = ( { 'mainMenuOption':'Cereal', 'subMenuOptions': ('Saltana Bran', 'Wheat Biscuits') }, { 'mainMenuOption':'Fruit', 'subMenuOptions': ('Apple', 'Banana', 'Mandarine') } ) print (menuWithSubmenus('Meal/Snack Type',menuItems))
-
This is pretty nice, especially for someone who hasn't used Python that long yet. :) It does indeed work properly in Pythonista as well - even in Python 3.
Regarding the code style, here are a few small suggestions:
- In Python, variable/function/method/parameter names are usually written in
snake_case
, rather thandromedaryCase
as is common in Java and such. - The
multiple
parameter ofdialogs.list_dialog
defaults toFalse
, so you don't need to explicitly set it toFalse
for each call. - Using a dictionary to return multiple values isn't usually done in Python. This is in part because Python has no easy way to "unpack" multiple values from a dictionary - instead you need to store the dictionary in a variable, and then access each value individually. If you have a small, fixed number of return values, you can return a tuple, which can be easily unpacked like
main_option, sub_option = menu_with_submenus(...)
. You can also usecollections.namedtuple
to make a custom tuple type with named fields. If you have more than a few fields, you might want to write a class instead (but that's probably overkill in this case).
- In Python, variable/function/method/parameter names are usually written in
-
Thanks, that's really helpful :)