Python: how to use list as source of selection for user input?

非 Y 不嫁゛ 提交于 2021-02-06 04:22:22

问题


Can anyone check this code and let me know what is wrong?

input_list = ["One", "Two", "Three"]
P1 = input("Select the input: ", input_list[0], input_list[1], input_list[2])
print (P1)

回答1:


With python's raw_input it is not possible to give a preselected list to the user to choose from. With raw_input we collect raw strings.

update: a nice solution is to use the new pick library: https://github.com/wong2/pick It provides a small curses interface to pick our choice from a given list. Get it with pip install pick. (update: multi-select: yes)

update 2: and yet another python lib ! https://curses-menu.readthedocs.org/en/latest/usage.html#getting-a-selection (no multi-select)

There's a tiny and unmaintained library made for that purpose, picker (multi-select: yes).

The simplest solution I'm thinking of is to use shell tools:

  • dialog is what distros like Debian use to present UIs in the console,
  • selecta is a fuzzy text selector for the shell, so it fits exactly our needs, except it is a ruby tool,
  • zenity (and yad-dialog) make it very easy to build simple windows (we exit the terminal). I can display a list with this:

    zenity --list --text="a title" --column="first column" "first choice" "second choice"
    

    We can also select multiple choices.

  • if we exit the console, we can use more complete GUI tools like gooey (it turns a python script with command line arguments into a GUI) or even Flexxx and others, but that's another work.



回答2:


Take a look at the documentation of the input function: https://docs.python.org/2/library/functions.html#input

input presents a prompt and evaluates the data input by the user as if it were a Python expression. If you just want to gather data input by the user, use raw_input instead. You'll need to implement custom logic to make sure the user's input matches with something in your list.



来源:https://stackoverflow.com/questions/28425204/python-how-to-use-list-as-source-of-selection-for-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!