checkbox

A prompt which displays a list of checkboxes to toggle/tick.

Example

demo

Classic Syntax (PyInquirer)
from InquirerPy import prompt
from InquirerPy.base import Choice
from InquirerPy.separator import Separator

question1_choice = [
    Separator(),
    Choice("ap-southeast-2", name="Sydney", enabled=True),
    Choice("ap-southeast-1", name="Singapore", enabled=False),
    Separator(),
    "us-east-1",
    "us-west-1",
    Separator(),
]


def question2_choice(_):
    return [
        "Apple",
        "Cherry",
        "Orange",
        "Peach",
        "Melon",
        "Strawberry",
        "Grapes",
    ]


def main():
    questions = [
        {
            "type": "checkbox",
            "message": "Select regions:",
            "choices": question1_choice,
            "transformer": lambda result: "%s region%s selected"
            % (len(result), "s" if len(result) > 1 else ""),
        },
        {
            "type": "checkbox",
            "message": "Pick your favourites:",
            "choices": question2_choice,
            "validate": lambda result: len(result) >= 1,
            "invalid_message": "should be at least 1 selection",
            "instruction": "(select at least 1)",
        },
    ]

    result = prompt(questions)


if __name__ == "__main__":
    main()
Alternate Syntax
from InquirerPy import inquirer
from InquirerPy.base.control import Choice
from InquirerPy.separator import Separator

question1_choice = [
    Separator(),
    Choice("ap-southeast-2", name="Sydney", enabled=True),
    Choice("ap-southeast-1", name="Singapore", enabled=False),
    Separator(),
    "us-east-1",
    "us-west-1",
    Separator(),
]


def question2_choice(_):
    return [
        "Apple",
        "Cherry",
        "Orange",
        "Peach",
        "Melon",
        "Strawberry",
        "Grapes",
    ]


def main():
    regions = inquirer.checkbox(
        message="Select regions:",
        choices=question1_choice,
        cycle=False,
        transformer=lambda result: "%s region%s selected"
        % (len(result), "s" if len(result) > 1 else ""),
    ).execute()
    fruits = inquirer.checkbox(
        message="Pick your favourites:",
        choices=question2_choice,
        validate=lambda result: len(result) >= 1,
        invalid_message="should be at least 1 selection",
        instruction="(select at least 1)",
    ).execute()


if __name__ == "__main__":
    main()

Choices

See also

choices

In checkbox prompt, the multiselct option is always enabled. If you want any choices to be pre-selected, use Choice to create choices and set enabled to True.

from InquirerPy.base import Choice

choices = [
    Choice("selected", enabled=True),
    Choice("notselected", enabled=False),
    "notselected2"
]

Keybindings

See also

keybindings

{
    "answer": [{"key": "enter"}],   # answer the prompt
    "interrupt": [{"key": "c-c"}],  # raise KeyboardInterrupt
    "skip": [{"key": "c-z"}],   # skip the prompt
}

The following dictionary contains the additional keybindings created by this prompt.

{
    "down": [
        {"key": "down"},
        {"key": "c-n"},   # move down
    ],
    "up": [
        {"key": "up"},
        {"key": "c-p"},   # move up
    ],
    "toggle": [
        {"key": "space"},   # toggle choices
    ],
    "toggle-down": [
        {"key": "c-i"},   # toggle choice and move down (tab)
    ],
    "toggle-up": [
        {"key": "s-tab"},   # toggle choice and move up (shift+tab)
    ],
    "toggle-all": [
        {"key": "alt-r"},   # toggle all choices
        {"key": "c-r"},
    ],
    "toggle-all-true": [
        {"key": "alt-a"},   # toggle all choices true
        {"key": "c-a"}.
    ],
    "toggle-all-false": [],   # toggle all choices false
}

When vi_mode is True, the “up” and “down” navigation key will be changed.

{
    "down": [
        {"key": "down"},
        {"key": "j"},
    ],
    "up": [
        {"key": "up"},
        {"key": "k"},
    ],
}

Default Value

See also

default

The default parameter will be used to determine which choice is highlighted by default.

It should be the value of one of the choices.

If you wish to pre-select certain choices, you can leverage the enabled parameter/key of each choice.

from InquirerPy.base import Choice

choices = [
    Choice(1, enabled=True),  # enabled by default
    Choice(2)  # not enabled
]

Reference

class InquirerPy.prompts.checkbox.CheckboxPrompt(message, choices, default=None, style=None, vi_mode=False, qmark='?', amark='?', pointer='❯', enabled_symbol='◉', disabled_symbol='○', border=False, instruction='', long_instruction='', transformer=None, filter=None, height=None, max_height=None, validate=None, invalid_message='Invalid input', keybindings=None, show_cursor=True, cycle=True, wrap_lines=True, raise_keyboard_interrupt=True, mandatory=True, mandatory_message='Mandatory prompt', session_result=None)[source]

Create a prompt which displays a list of checkboxes to toggle.

A wrapper class around Application.

User can toggle on/off on each checkbox.

Works very similar to ListPrompt with multiselect enabled, the main difference is visual/UI and also when not toggling anything, the result will be empty.

Parameters
  • message (Union[str, Callable[[InquirerPySessionResult], str]]) – The question to ask the user. Refer to message documentation for more details.

  • choices (Union[Callable[[InquirerPySessionResult], Union[List[Any], List[Choice], List[Dict[str, Any]]]], List[Any], List[Choice], List[Dict[str, Any]]]) – List of choices to display and select. Refer to choices documentation for more details.

  • style (Optional[InquirerPy.utils.InquirerPyStyle]) – An InquirerPyStyle instance. Refer to Style documentation for more details.

  • vi_mode (bool) – Use vim keybinding for the prompt. Refer to keybindings documentation for more details.

  • default (Any) – Set the default value of the prompt. This will be used to determine which choice is highlighted (current selection), The default value should be the value of one of the choices. Refer to default documentation for more details.

  • separator – Separator symbol. Custom symbol that will be used as a separator between the choice index number and the choices.

  • qmark (str) – Question mark symbol. Custom symbol that will be displayed infront of the question before its answered.

  • amark (str) – Answer mark symbol. Custom symbol that will be displayed infront of the question after its answered.

  • pointer (str) – Pointer symbol. Customer symbol that will be used to indicate the current choice selection.

  • enabled_symbol (str) – Checkbox ticked symbol. Custom symbol which indicate the checkbox is ticked.

  • disabled_symbol (str) – Checkbox not ticked symbol. Custom symbol which indicate the checkbox is not ticked.

  • instruction (str) – Short instruction to display next to the question.

  • long_instruction (str) – Long instructions to display at the bottom of the prompt.

  • validate (Optional[Union[Callable[[Any], bool], Validator]]) – Add validation to user input. The main use case for this prompt would be when multiselect is True, you can enforce a min/max selection. Refer to Validator documentation for more details.

  • invalid_message (str) – Error message to display when user input is invalid. Refer to Validator documentation for more details.

  • transformer (Optional[Callable[[Any], Any]]) – A function which performs additional transformation on the value that gets printed to the terminal. Different than filter parameter, this is only visual effect and won’t affect the actual value returned by execute(). Refer to transformer documentation for more details.

  • filter (Optional[Callable[[Any], Any]]) – A function which performs additional transformation on the result. This affects the actual value returned by execute(). Refer to filter documentation for more details.

  • height (Optional[Union[int, str]]) – Preferred height of the prompt. Refer to height documentation for more details.

  • max_height (Optional[Union[int, str]]) – Max height of the prompt. Refer to height documentation for more details.

  • border (bool) – Create border around the choice window.

  • keybindings (Optional[Dict[str, List[Dict[str, Union[str, FilterOrBool, List[str]]]]]]) – Customise the builtin keybindings. Refer to keybindings for more details.

  • show_cursor (bool) – Display cursor at the end of the prompt. Set to False to hide the cursor.

  • cycle (bool) – Return to top item if hit bottom during navigation or vice versa.

  • wrap_lines (bool) – Soft wrap question lines when question exceeds the terminal width.

  • raise_keyboard_interrupt (bool) – Raise the KeyboardInterrupt exception when ctrl-c is pressed. If false, the result will be None and the question is skiped.

  • mandatory (bool) – Indicate if the prompt is mandatory. If True, then the question cannot be skipped.

  • mandatory_message (str) – Error message to show when user attempts to skip mandatory prompt.

  • session_result (Optional[Dict[Union[str, int], Optional[Union[str, bool, List[Any]]]]]) – Used internally for Classic Syntax (PyInquirer).

Return type

None

Examples

>>> from InquirerPy import inquirer
>>> result = inquirer.checkbox(message="Select:", choices=[1, 2, 3]).execute()
>>> print(result)
[1]