Can I make multiple choice input in Python?

I am asking can I print something like this:

>Do action one
 Do action two

Than i press downarrow:

 Do action one
>Do action two

Then I press enter and it chooses action two and does somehing.

How would I do something like this in Python, is there some module to do this. Sorry if you don't understand what I am saying English isn't my first language

Posted Mar 17, 2018, 4:01 PM UTC

26
ImportBracesfrom __future__ import braces•

This howto covers the curses library, which supports that. Is that what you were looking for?

5
peroz1OP•

Thanks, I will check it out

1
Vaphell•

If you mean the terminal window, you can, but it's not trivial. The default mode of showing stuff in terminal is like in a oldschool printer using "infinite" sheet of paper (which is what terminals pretty much emulate), where you print rows and the notion of going up/down is pretty much non-existent.
You need to use something like curses, urwid etc which use lower level hackery allowing to control the terminal to provide some sort of widgets.

If you don't care about it happening in terminal you could use some gui framework like tkinter, drawing a window with lists, checkboxes and what not.

the fastest way to implement the core functionality of multiple selection would be to just print menu and allow user to type in multiple numbers, eg

1. menu item 1
2. menu item 2
3. menu item 3
4. menu item 4
choice: 1 3

choices = input('choice: ')
selected = [int(x) for x in choices.split()]

yes, it's crude but it works. Once you got that and the rest of program's functionality down, you can make it prettier with fancier solutions.

2
peroz1OP•

I already have something like that in my program but I wanted to see if I can implement this. But I will look at those modules to see what I can do, thanks

1
Vaphell•

minimal example using tkinter

#!/usr/bin/env python3

import tkinter as tk

def onselect(event):
    print('onselect: ', menu.curselection())

root = tk.Tk()

menu = tk.Listbox(root, selectmode = tk.MULTIPLE)
for i in range(10):
    menu.insert(i, 'menu item[{}]'.format(i))
menu.bind('<<ListboxSelect>>', onselect)
menu.pack()

root.mainloop()

onselect is bound to the listboxselect event and run every time it occurs. It's not necessary here per se, but it's nice to see the feedback. Listbox.curselection gives you the current state of selection in the form of a tuple of indices. Add some button finalizing the selection and you are golden.

2
peroz1OP•

Thank you. I am still a begginer and I haven't yet worked with tkinter but I will check it out

1