[go: up one dir, main page]

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 Text) 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 ────────────────────────────────────────────────────────────── ^p palette

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 ────────────────────────────────────────────────────────────── ^p palette

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 ────────────────────────────── ^p palette

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

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--separator Target the separators.

Bases: Generic[SelectionType], OptionList

A vertical selection list that allows making multiple selections.

Parameters:

Name Type Description Default

*selections

Selection[SelectionType] | tuple[TextType, SelectionType] | tuple[TextType, SelectionType, bool]

The content for the selection list.

()

name

str | None

The name of the selection list.

None

id

str | None

The ID of the selection list in the DOM.

None

classes

str | None

The CSS classes of the selection list.

None

disabled

bool

Whether the selection list is disabled or not.

False

BINDINGS class-attribute instance-attribute

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

COMPONENT_CLASSES class-attribute

COMPONENT_CLASSES = {
    "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

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 dataclass

SelectedChanged(selection_list)

Bases: Generic[MessageSelectionType], Message

Message sent when the collection of selected values changes.

This is sent regardless of whether the change occurred via user interaction or programmatically the the SelectionList API.

When a bulk change occurs, such as through select_all or deselect_all, only a single SelectedChanged message will be sent (rather than one per option).

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

control property

control

An alias for selection_list.

selection_list instance-attribute

selection_list

The SelectionList that sent the message.

SelectionHighlighted

SelectionHighlighted(selection_list, index)

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.

Parameters:

Name Type Description Default

selection_list

SelectionList[MessageSelectionType]

The selection list that owns the selection.

required

index

int

The index of the selection that the message relates to.

required

SelectionMessage

SelectionMessage(selection_list, index)

Bases: Generic[MessageSelectionType], Message

Base class for all selection messages.

Parameters:

Name Type Description Default

selection_list

SelectionList[MessageSelectionType]

The selection list that owns the selection.

required

index

int

The index of the selection that the message relates to.

required

control property

control

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 = get_option_at_index(index)

The highlighted selection.

selection_index instance-attribute

selection_index = index

The index of the selection that the message relates to.

selection_list instance-attribute

selection_list = selection_list

The selection list that sent the message.

SelectionToggled

SelectionToggled(selection_list, index)

Bases: SelectionMessage[MessageSelectionType]

Message sent when a selection is toggled.

This is only sent when the value is explicitly toggled e.g. via toggle or toggle_all, or via user interaction. If you programmatically set a value to be selected, this message will not be sent, even if it happens to be the opposite of what was originally selected (i.e. setting a True to a False or vice-versa).

Since this message indicates a toggle occurring at a per-option level, a message will be sent for each option that is toggled, even when a bulk action is performed (e.g. via toggle_all).

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

Parameters:

Name Type Description Default

selection_list

SelectionList[MessageSelectionType]

The selection list that owns the selection.

required

index

int

The index of the selection that the message relates to.

required

add_option

add_option(item=None)

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

Parameters:

Name Type Description Default

item

NewOptionListContent | Selection | tuple[TextType, SelectionType] | tuple[TextType, SelectionType, bool]

The new item to add.

None

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

add_options(items)

Add new selection options to the end of the list.

Parameters:

Name Type Description Default

items

Iterable[NewOptionListContent | Selection[SelectionType] | tuple[TextType, SelectionType] | tuple[TextType, SelectionType, bool]]

The new items to add.

required

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

clear_options()

Clear the content of the selection list.

Returns:

Type Description
Self

The SelectionList instance.

deselect

deselect(selection)

Mark the given selection as not selected.

Parameters:

Name Type Description Default

selection

Selection[SelectionType] | SelectionType

The selection to mark as not selected.

required

Returns:

Type Description
Self

The SelectionList instance.

deselect_all

deselect_all()

Deselect all items.

Returns:

Type Description
Self

The SelectionList instance.

get_option

get_option(option_id)

Get the selection option with the given ID.

Parameters:

Name Type Description Default

option_id

str

The ID of the selection option to get.

required

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

get_option_at_index(index)

Get the selection option at the given index.

Parameters:

Name Type Description Default

index

int

The index of the selection option to get.

required

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

select(selection)

Mark the given selection as selected.

Parameters:

Name Type Description Default

selection

Selection[SelectionType] | SelectionType

The selection to mark as selected.

required

Returns:

Type Description
Self

The SelectionList instance.

select_all

select_all()

Select all items.

Returns:

Type Description
Self

The SelectionList instance.

toggle

toggle(selection)

Toggle the selected state of the given selection.

Parameters:

Name Type Description Default

selection

Selection[SelectionType] | SelectionType

The selection to toggle.

required

Returns:

Type Description
Self

The SelectionList instance.

toggle_all

toggle_all()

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

Selection(
    prompt,
    value,
    initial_state=False,
    id=None,
    disabled=False,
)

Bases: Generic[SelectionType], Option

A selection for a SelectionList.

Parameters:

Name Type Description Default

prompt

TextType

The prompt for the selection.

required

value

SelectionType

The value for the selection.

required

initial_state

bool

The initial selected state of the selection.

False

id

str | None

The optional ID for the selection.

None

disabled

bool

The initial enabled/disabled state. Enabled by default.

False

initial_state property

initial_state

The initial selected state for the selection.

value property

value

The value for this selection.

SelectionError

Bases: TypeError

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