Skip to content

SelectionList

Added in version 0.27.0

A widget for showing a vertical list of selectable options.

  • Focusable
  • Container

Typing

The SelectionList control is a Generic, which allows you to set the type of the selection values. For instance, if the data type for your values is an integer, you would type the widget as follows:

selections = [("First", 1), ("Second", 2)]
my_selection_list: SelectionList[int] =  SelectionList(*selections)

Note

Typing is entirely optional.

If you aren't familiar with typing or don't want to worry about it right now, feel free to ignore it.

Examples

A selection list is designed to be built up of single-line prompts (which can be Rich renderables) and an associated unique value.

Selections as tuples

A selection list can be built with tuples, either of two or three values in length. Each tuple must contain a prompt and a value, and it can also optionally contain a flag for the initial selected state of the option.

SelectionListApp SelectionListApp  Shall we play some games? ────────────────────────────────── XFalken's Maze XBlack Jack XGin Rummy XHearts XBridge XCheckers XChess XPoker XFighter Combat ──────────────────────────────────────────────────────────────

from textual.app import App, ComposeResult
from textual.widgets import Footer, Header, SelectionList


class SelectionListApp(App[None]):
    CSS_PATH = "selection_list.tcss"

    def compose(self) -> ComposeResult:
        yield Header()
        yield SelectionList[int](  # (1)!
            ("Falken's Maze", 0, True),
            ("Black Jack", 1),
            ("Gin Rummy", 2),
            ("Hearts", 3),
            ("Bridge", 4),
            ("Checkers", 5),
            ("Chess", 6, True),
            ("Poker", 7),
            ("Fighter Combat", 8, True),
        )
        yield Footer()

    def on_mount(self) -> None:
        self.query_one(SelectionList).border_title = "Shall we play some games?"


if __name__ == "__main__":
    SelectionListApp().run()
  1. Note that the SelectionList is typed as int, for the type of the values.
Screen {
    align: center middle;
}

SelectionList {
    padding: 1;
    border: solid $accent;
    width: 80%;
    height: 80%;
}

Selections as Selection objects

Alternatively, selections can be passed in as Selections:

SelectionListApp SelectionListApp  Shall we play some games? ────────────────────────────────── XFalken's Maze XBlack Jack XGin Rummy XHearts XBridge XCheckers XChess XPoker XFighter Combat ──────────────────────────────────────────────────────────────

from textual.app import App, ComposeResult
from textual.widgets import Footer, Header, SelectionList
from textual.widgets.selection_list import Selection


class SelectionListApp(App[None]):
    CSS_PATH = "selection_list.tcss"

    def compose(self) -> ComposeResult:
        yield Header()
        yield SelectionList[int](  # (1)!
            Selection("Falken's Maze", 0, True),
            Selection("Black Jack", 1),
            Selection("Gin Rummy", 2),
            Selection("Hearts", 3),
            Selection("Bridge", 4),
            Selection("Checkers", 5),
            Selection("Chess", 6, True),
            Selection("Poker", 7),
            Selection("Fighter Combat", 8, True),
        )
        yield Footer()

    def on_mount(self) -> None:
        self.query_one(SelectionList).border_title = "Shall we play some games?"


if __name__ == "__main__":
    SelectionListApp().run()
  1. Note that the SelectionList is typed as int, for the type of the values.
Screen {
    align: center middle;
}

SelectionList {
    padding: 1;
    border: solid $accent;
    width: 80%;
    height: 80%;
}

Handling changes to the selections

Most of the time, when using the SelectionList, you will want to know when the collection of selected items has changed; this is ideally done using the SelectedChanged message. Here is an example of using that message to update a Pretty with the collection of selected values:

SelectionListApp SelectionListApp  Shall we play some games? ── Selected games ───────────── [ XFalken's Maze'secret_back_door', XBlack Jack'a_nice_game_of_chess', XGin Rummy'fighter_combat' XHearts] XBridge────────────────────────────── XCheckers XChess XPoker XFighter Combat ──────────────────────────────

from textual import on
from textual.app import App, ComposeResult
from textual.containers import Horizontal
from textual.events import Mount
from textual.widgets import Footer, Header, Pretty, SelectionList
from textual.widgets.selection_list import Selection


class SelectionListApp(App[None]):
    CSS_PATH = "selection_list_selected.tcss"

    def compose(self) -> ComposeResult:
        yield Header()
        with Horizontal():
            yield SelectionList[str](  # (1)!
                Selection("Falken's Maze", "secret_back_door", True),
                Selection("Black Jack", "black_jack"),
                Selection("Gin Rummy", "gin_rummy"),
                Selection("Hearts", "hearts"),
                Selection("Bridge", "bridge"),
                Selection("Checkers", "checkers"),
                Selection("Chess", "a_nice_game_of_chess", True),
                Selection("Poker", "poker"),
                Selection("Fighter Combat", "fighter_combat", True),
            )
            yield Pretty([])
        yield Footer()

    def on_mount(self) -> None:
        self.query_one(SelectionList).border_title = "Shall we play some games?"
        self.query_one(Pretty).border_title = "Selected games"

    @on(Mount)
    @on(SelectionList.SelectedChanged)
    def update_selected_view(self) -> None:
        self.query_one(Pretty).update(self.query_one(SelectionList).selected)


if __name__ == "__main__":
    SelectionListApp().run()
  1. Note that the SelectionList is typed as str, for the type of the values.
Screen {
    align: center middle;
}

Horizontal {
    width: 80%;
    height: 80%;
}

SelectionList {
    padding: 1;
    border: solid $accent;
    width: 1fr;
}

Pretty {
    width: 1fr;
    border: solid $accent;
}

Reactive Attributes

Name Type Default Description
highlighted int | None None The index of the highlighted selection. None means nothing is highlighted.

Messages

The following messages will be posted as the user interacts with the list:

The following message will be posted if the content of selected changes, either by user interaction or by API calls:

Bindings

The selection list widget defines the following bindings:

Key(s) Description
space Toggle the state of the highlighted selection.

It inherits from OptionList and so also inherits the following bindings:

Key(s) Description
down Move the highlight down.
end Move the highlight to the last option.
enter Select the current option.
home Move the highlight to the first option.
pagedown Move the highlight down a page of options.
pageup Move the highlight up a page of options.
up Move the highlight up.

Component Classes

The selection list provides the following component classes:

Class Description
selection-list--button Target the default button style.
selection-list--button-selected Target a selected button style.
selection-list--button-highlighted Target a highlighted button style.
selection-list--button-selected-highlighted Target a highlighted selected button style.

It inherits from OptionList and so also makes use of the following component classes:

Class Description
option-list--option-disabled Target disabled options.
option-list--option-highlighted Target the highlighted option.
option-list--option-hover Target an option that has the mouse over it.
option-list--option-hover-highlighted Target a highlighted option that has the mouse over it.
option-list--separator Target the separators.

textual.widgets.SelectionList class

def __init__(
    self,
    *selections,
    name=None,
    id=None,
    classes=None,
    disabled=False
):

Bases: Generic[SelectionType], OptionList

A vertical selection list that allows making multiple selections.

Parameters
Parameter Default Description
*selections
Selection[SelectionType] | tuple[TextType, SelectionType] | tuple[TextType, SelectionType, bool]
()

The content for the selection list.

name
str | None
None

The name of the selection list.

id
str | None
None

The ID of the selection list in the DOM.

classes
str | None
None

The CSS classes of the selection list.

disabled
bool
False

Whether the selection list is disabled or not.

BINDINGS class-attribute instance-attribute

BINDINGS = [Binding('space', 'select')]
Key(s) Description
space Toggle the state of the highlighted selection.

COMPONENT_CLASSES class-attribute

COMPONENT_CLASSES: set[str] = {
    "selection-list--button",
    "selection-list--button-selected",
    "selection-list--button-highlighted",
    "selection-list--button-selected-highlighted",
}
Class Description
selection-list--button Target the default button style.
selection-list--button-selected Target a selected button style.
selection-list--button-highlighted Target a highlighted button style.
selection-list--button-selected-highlighted Target a highlighted selected button style.

selected property

selected: list[SelectionType]

The selected values.

This is a list of all of the values associated with selections in the list that are currently in the selected state.

SelectedChanged class

Bases: Generic[MessageSelectionType], Message

Message sent when the collection of selected values changes.

This message is sent when any change to the collection of selected values takes place; either by user interaction or by API calls.

control property

control: SelectionList[MessageSelectionType]

An alias for selection_list.

selection_list instance-attribute

selection_list: SelectionList[MessageSelectionType]

The SelectionList that sent the message.

SelectionHighlighted class

Bases: SelectionMessage[MessageSelectionType]

Message sent when a selection is highlighted.

Can be handled using on_selection_list_selection_highlighted in a subclass of SelectionList or in a parent node in the DOM.

SelectionMessage class

def __init__(self, selection_list, index):

Bases: Generic[MessageSelectionType], Message

Base class for all selection messages.

Parameters
Parameter Default Description
selection_list
SelectionList[MessageSelectionType]
required

The selection list that owns the selection.

index
int
required

The index of the selection that the message relates to.

control property

control: OptionList

The selection list that sent the message.

This is an alias for SelectionMessage.selection_list and is used by the on decorator.

selection instance-attribute

selection: Selection[MessageSelectionType] = (
    selection_list.get_option_at_index(index)
)

The highlighted selection.

selection_index instance-attribute

selection_index: int = index

The index of the selection that the message relates to.

selection_list instance-attribute

selection_list: SelectionList[MessageSelectionType] = (
    selection_list
)

The selection list that sent the message.

SelectionToggled class

Bases: SelectionMessage[MessageSelectionType]

Message sent when a selection is toggled.

Can be handled using on_selection_list_selection_toggled in a subclass of SelectionList or in a parent node in the DOM.

Note

This message is only sent if the selection is toggled by user interaction. See SelectedChanged for a message sent when any change (selected or deselected, either by user interaction or by API calls) is made to the selected values.

add_option method

def add_option(self, item=None):

Add a new selection option to the end of the list.

Parameters
Parameter Default Description
item
NewOptionListContent | Selection | tuple[TextType, SelectionType] | tuple[TextType, SelectionType, bool]
None

The new item to add.

Returns
Type Description
Self

The SelectionList instance.

Raises
Type Description
DuplicateID

If there is an attempt to use a duplicate ID.

SelectionError

If the selection option is of the wrong form.

add_options method

def add_options(self, items):

Add new selection options to the end of the list.

Parameters
Parameter Default Description
items
Iterable[NewOptionListContent | Selection[SelectionType] | tuple[TextType, SelectionType] | tuple[TextType, SelectionType, bool]]
required

The new items to add.

Returns
Type Description
Self

The SelectionList instance.

Raises
Type Description
DuplicateID

If there is an attempt to use a duplicate ID.

SelectionError

If one of the selection options is of the wrong form.

clear_options method

def clear_options(self):

Clear the content of the selection list.

Returns
Type Description
Self

The SelectionList instance.

deselect method

def deselect(self, selection):

Mark the given selection as not selected.

Parameters
Parameter Default Description
selection
Selection[SelectionType] | SelectionType
required

The selection to mark as not selected.

Returns
Type Description
Self

The SelectionList instance.

deselect_all method

def deselect_all(self):

Deselect all items.

Returns
Type Description
Self

The SelectionList instance.

get_option method

def get_option(self, option_id):

Get the selection option with the given ID.

Parameters
Parameter Default Description
option_id
str
required

The ID of the selection option to get.

Returns
Type Description
Selection[SelectionType]

The selection option with the ID.

Raises
Type Description
OptionDoesNotExist

If no selection option has the given ID.

get_option_at_index method

def get_option_at_index(self, index):

Get the selection option at the given index.

Parameters
Parameter Default Description
index
int
required

The index of the selection option to get.

Returns
Type Description
Selection[SelectionType]

The selection option at that index.

Raises
Type Description
OptionDoesNotExist

If there is no selection option with the index.

select method

def select(self, selection):

Mark the given selection as selected.

Parameters
Parameter Default Description
selection
Selection[SelectionType] | SelectionType
required

The selection to mark as selected.

Returns
Type Description
Self

The SelectionList instance.

select_all method

def select_all(self):

Select all items.

Returns
Type Description
Self

The SelectionList instance.

toggle method

def toggle(self, selection):

Toggle the selected state of the given selection.

Parameters
Parameter Default Description
selection
Selection[SelectionType] | SelectionType
required

The selection to toggle.

Returns
Type Description
Self

The SelectionList instance.

toggle_all method

def toggle_all(self):

Toggle all items.

Returns
Type Description
Self

The SelectionList instance.

MessageSelectionType module-attribute

MessageSelectionType = TypeVar('MessageSelectionType')

The type for the value of a Selection in a SelectionList message.

SelectionType module-attribute

SelectionType = TypeVar('SelectionType')

The type for the value of a Selection in a SelectionList

Selection class

def __init__(
    self,
    prompt,
    value,
    initial_state=False,
    id=None,
    disabled=False,
):

Bases: Generic[SelectionType], Option

A selection for a SelectionList.

Parameters
Parameter Default Description
prompt
TextType
required

The prompt for the selection.

value
SelectionType
required

The value for the selection.

initial_state
bool
False

The initial selected state of the selection.

id
str | None
None

The optional ID for the selection.

disabled
bool
False

The initial enabled/disabled state. Enabled by default.

initial_state property

initial_state: bool

The initial selected state for the selection.

value property

value: SelectionType

The value for this selection.

SelectionError class

Bases: TypeError

Type of an error raised if a selection is badly-formed.