Skip to content

OptionList

Added in version 0.17.0

A widget for showing a vertical list of Rich renderable options.

  • Focusable
  • Container

Examples

Options as simple strings

An OptionList can be constructed with a simple collection of string options:

OptionListApp OptionListApp ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ Aerilon Aquaria Canceron Caprica Gemenon Leonis Libran Picon Sagittaron Scorpia Tauron Virgon ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁

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


class OptionListApp(App[None]):
    CSS_PATH = "option_list.tcss"

    def compose(self) -> ComposeResult:
        yield Header()
        yield OptionList(
            "Aerilon",
            "Aquaria",
            "Canceron",
            "Caprica",
            "Gemenon",
            "Leonis",
            "Libran",
            "Picon",
            "Sagittaron",
            "Scorpia",
            "Tauron",
            "Virgon",
        )
        yield Footer()


if __name__ == "__main__":
    OptionListApp().run()
Screen {
    align: center middle;
}

OptionList {
    width: 70%;
    height: 80%;
}

Options as Option instances

For finer control over the options, the Option class can be used; this allows for setting IDs, setting initial disabled state, etc. The Separator class can be used to add separator lines between options.

OptionListApp OptionListApp ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ Aerilon Aquaria ────────────────────────────────────────────────── Canceron Caprica ────────────────────────────────────────────────── Gemenon ────────────────────────────────────────────────── Leonis Libran ────────────────────────────────────────────────── Picon▁▁ ────────────────────────────────────────────────── Sagittaron Scorpia ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁

from textual.app import App, ComposeResult
from textual.widgets import Footer, Header, OptionList
from textual.widgets.option_list import Option, Separator


class OptionListApp(App[None]):
    CSS_PATH = "option_list.tcss"

    def compose(self) -> ComposeResult:
        yield Header()
        yield OptionList(
            Option("Aerilon", id="aer"),
            Option("Aquaria", id="aqu"),
            Separator(),
            Option("Canceron", id="can"),
            Option("Caprica", id="cap", disabled=True),
            Separator(),
            Option("Gemenon", id="gem"),
            Separator(),
            Option("Leonis", id="leo"),
            Option("Libran", id="lib"),
            Separator(),
            Option("Picon", id="pic"),
            Separator(),
            Option("Sagittaron", id="sag"),
            Option("Scorpia", id="sco"),
            Separator(),
            Option("Tauron", id="tau"),
            Separator(),
            Option("Virgon", id="vir"),
        )
        yield Footer()


if __name__ == "__main__":
    OptionListApp().run()
Screen {
    align: center middle;
}

OptionList {
    width: 70%;
    height: 80%;
}

Options as Rich renderables

Because the prompts for the options can be Rich renderables, this means they can be any height you wish. As an example, here is an option list comprised of Rich tables:

OptionListApp OptionListApp ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔                  Data for Aerilon                  ┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┓ Patron God   Population   Capital City   ┡━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━┩▇▇ Demeter      1.2 Billion  Gaoth          └───────────────┴───────────────┴────────────────┘                  Data for Aquaria                  ┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┓ Patron God   Population   Capital City   ┡━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━┩ Hermes       75,000       None           └───────────────┴───────────────┴────────────────┘                 Data for Canceron                  ┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┓ Patron God   Population   Capital City   ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁

from __future__ import annotations

from rich.table import Table

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

COLONIES: tuple[tuple[str, str, str, str], ...] = (
    ("Aerilon", "Demeter", "1.2 Billion", "Gaoth"),
    ("Aquaria", "Hermes", "75,000", "None"),
    ("Canceron", "Hephaestus", "6.7 Billion", "Hades"),
    ("Caprica", "Apollo", "4.9 Billion", "Caprica City"),
    ("Gemenon", "Hera", "2.8 Billion", "Oranu"),
    ("Leonis", "Artemis", "2.6 Billion", "Luminere"),
    ("Libran", "Athena", "2.1 Billion", "None"),
    ("Picon", "Poseidon", "1.4 Billion", "Queenstown"),
    ("Sagittaron", "Zeus", "1.7 Billion", "Tawa"),
    ("Scorpia", "Dionysus", "450 Million", "Celeste"),
    ("Tauron", "Ares", "2.5 Billion", "Hypatia"),
    ("Virgon", "Hestia", "4.3 Billion", "Boskirk"),
)


class OptionListApp(App[None]):
    CSS_PATH = "option_list.tcss"

    @staticmethod
    def colony(name: str, god: str, population: str, capital: str) -> Table:
        table = Table(title=f"Data for {name}", expand=True)
        table.add_column("Patron God")
        table.add_column("Population")
        table.add_column("Capital City")
        table.add_row(god, population, capital)
        return table

    def compose(self) -> ComposeResult:
        yield Header()
        yield OptionList(*[self.colony(*row) for row in COLONIES])
        yield Footer()


if __name__ == "__main__":
    OptionListApp().run()
Screen {
    align: center middle;
}

OptionList {
    width: 70%;
    height: 80%;
}

Reactive Attributes

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

Messages

Both of the messages above inherit from the common base OptionList.OptionMessage, so refer to its documentation to see what attributes are available.

Bindings

The option list widget defines 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 option list provides 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.OptionList class

def __init__(
    self,
    *content,
    name=None,
    id=None,
    classes=None,
    disabled=False,
    wrap=True
):

Bases: ScrollView

A vertical option list with bounce-bar highlighting.

Parameters
Parameter Default Description
*content
NewOptionListContent
()

The content for the option list.

name
str | None
None

The name of the option list.

id
str | None
None

The ID of the option list in the DOM.

classes
str | None
None

The CSS classes of the option list.

disabled
bool
False

Whether the option list is disabled or not.

wrap
bool
True

Should prompts be auto-wrapped?

BINDINGS class-attribute

BINDINGS: list[BindingType] = [
    Binding("down", "cursor_down", "Down", show=False),
    Binding("end", "last", "Last", show=False),
    Binding("enter", "select", "Select", show=False),
    Binding("home", "first", "First", show=False),
    Binding(
        "pagedown", "page_down", "Page Down", show=False
    ),
    Binding("pageup", "page_up", "Page Up", show=False),
    Binding("up", "cursor_up", "Up", show=False),
]
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 class-attribute

COMPONENT_CLASSES: set[str] = {
    "option-list--option",
    "option-list--option-disabled",
    "option-list--option-highlighted",
    "option-list--option-hover",
    "option-list--option-hover-highlighted",
    "option-list--separator",
}
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.

highlighted instance-attribute class-attribute

highlighted: reactive[int | None] = reactive["int | None"](
    None
)

The index of the currently-highlighted option, or None if no option is highlighted.

option_count property

option_count: int

The count of options.

OptionHighlighted class

Bases: OptionMessage

Message sent when an option is highlighted.

Can be handled using on_option_list_option_highlighted in a subclass of OptionList or in a parent node in the DOM.

OptionMessage class

def __init__(self, option_list, index):

Bases: Message

Base class for all option messages.

Parameters
Parameter Default Description
option_list
OptionList
required

The option list that owns the option.

index
int
required

The index of the option that the message relates to.

control property

control: OptionList

The option list that sent the message.

This is an alias for OptionMessage.option_list and is used by the on decorator.

option instance-attribute

option: Option = option_list.get_option_at_index(index)

The highlighted option.

option_id instance-attribute

option_id: str | None = self.option.id

The ID of the option that the message relates to.

option_index instance-attribute

option_index: int = index

The index of the option that the message relates to.

option_list instance-attribute

option_list: OptionList = option_list

The option list that sent the message.

OptionSelected class

Bases: OptionMessage

Message sent when an option is selected.

Can be handled using on_option_list_option_selected in a subclass of OptionList or in a parent node in the DOM.

action_cursor_down method

def action_cursor_down(self):

Move the highlight down to the next enabled option.

action_cursor_up method

def action_cursor_up(self):

Move the highlight up to the previous enabled option.

action_first method

def action_first(self):

Move the highlight to the first enabled option.

action_last method

def action_last(self):

Move the highlight to the last enabled option.

action_page_down method

def action_page_down(self):

Move the highlight down roughly by one page.

action_page_up method

def action_page_up(self):

Move the highlight up roughly by one page.

action_select method

def action_select(self):

Select the currently-highlighted option.

If no option is selected, then nothing happens. If an option is selected, a OptionList.OptionSelected message will be posted.

add_option method

def add_option(self, item=None):

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

Parameters
Parameter Default Description
item
NewOptionListContent
None

The new item to add.

Returns
Type Description
Self

The OptionList instance.

Raises
Type Description
DuplicateID

If there is an attempt to use a duplicate ID.

add_options method

def add_options(self, items):

Add new options to the end of the option list.

Parameters
Parameter Default Description
items
Iterable[NewOptionListContent]
required

The new items to add.

Returns
Type Description
Self

The OptionList instance.

Raises
Type Description
DuplicateID

If there is an attempt to use a duplicate ID.

Note

All options are checked for duplicate IDs before any option is added. A duplicate ID will cause none of the passed items to be added to the option list.

clear_options method

def clear_options(self):

Clear the content of the option list.

Returns
Type Description
Self

The OptionList instance.

disable_option method

def disable_option(self, option_id):

Disable the option with the given ID.

Parameters
Parameter Default Description
option_id
str
required

The ID of the option to disable.

Returns
Type Description
Self

The OptionList instance.

Raises
Type Description
OptionDoesNotExist

If no option has the given ID.

disable_option_at_index method

def disable_option_at_index(self, index):

Disable the option at the given index.

Returns
Type Description
Self

The OptionList instance.

Raises
Type Description
OptionDoesNotExist

If there is no option with the given index.

enable_option method

def enable_option(self, option_id):

Enable the option with the given ID.

Parameters
Parameter Default Description
option_id
str
required

The ID of the option to enable.

Returns
Type Description
Self

The OptionList instance.

Raises
Type Description
OptionDoesNotExist

If no option has the given ID.

enable_option_at_index method

def enable_option_at_index(self, index):

Enable the option at the given index.

Returns
Type Description
Self

The OptionList instance.

Raises
Type Description
OptionDoesNotExist

If there is no option with the given index.

get_option method

def get_option(self, option_id):

Get the option with the given ID.

Parameters
Parameter Default Description
option_id
str
required

The ID of the option to get.

Returns
Type Description
Option

The option with the ID.

Raises
Type Description
OptionDoesNotExist

If no option has the given ID.

get_option_at_index method

def get_option_at_index(self, index):

Get the option at the given index.

Parameters
Parameter Default Description
index
int
required

The index of the option to get.

Returns
Type Description
Option

The option at that index.

Raises
Type Description
OptionDoesNotExist

If there is no option with the given index.

get_option_index method

def get_option_index(self, option_id):

Get the index of the option with the given ID.

Parameters
Parameter Default Description
option_id
str
required

The ID of the option to get the index of.

Returns
Type Description
int

The index of the item with the given ID.

Raises
Type Description
OptionDoesNotExist

If no option has the given ID.

remove_option method

def remove_option(self, option_id):

Remove the option with the given ID.

Parameters
Parameter Default Description
option_id
str
required

The ID of the option to remove.

Returns
Type Description
Self

The OptionList instance.

Raises
Type Description
OptionDoesNotExist

If no option has the given ID.

remove_option_at_index method

def remove_option_at_index(self, index):

Remove the option at the given index.

Parameters
Parameter Default Description
index
int
required

The index of the option to remove.

Returns
Type Description
Self

The OptionList instance.

Raises
Type Description
OptionDoesNotExist

If there is no option with the given index.

replace_option_prompt method

def replace_option_prompt(self, option_id, prompt):

Replace the prompt of the option with the given ID.

Parameters
Parameter Default Description
option_id
str
required

The ID of the option to replace the prompt of.

prompt
RenderableType
required

The new prompt for the option.

Returns
Type Description
Self

The OptionList instance.

Raises
Type Description
OptionDoesNotExist

If no option has the given ID.

replace_option_prompt_at_index method

def replace_option_prompt_at_index(self, index, prompt):

Replace the prompt of the option at the given index.

Parameters
Parameter Default Description
index
int
required

The index of the option to replace the prompt of.

prompt
RenderableType
required

The new prompt for the option.

Returns
Type Description
Self

The OptionList instance.

Raises
Type Description
OptionDoesNotExist

If there is no option with the given index.

scroll_to_highlight method

def scroll_to_highlight(self, top=False):

Ensure that the highlighted option is in view.

Parameters
Parameter Default Description
top
bool
False

Scroll highlight to top of the list.

validate_highlighted method

def validate_highlighted(self, highlighted):

Validate the highlighted property value on access.

watch_highlighted method

def watch_highlighted(self, highlighted):

React to the highlighted option having changed.

watch_show_vertical_scrollbar method

def watch_show_vertical_scrollbar(self):

Handle the vertical scrollbar visibility status changing.

show_vertical_scrollbar is watched because it has an impact on the available width in which to render the renderables that make up the options in the list. If a vertical scrollbar appears or disappears we need to recalculate all the lines that make up the list.

DuplicateID class

Bases: Exception

Raised if a duplicate ID is used when adding options to an option list.

Option class

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

Class that holds the details of an individual option.

Parameters
Parameter Default Description
prompt
RenderableType
required

The prompt for the option.

id
str | None
None

The optional ID for the option.

disabled
bool
False

The initial enabled/disabled state. Enabled by default.

id property

id: str | None

The optional ID for the option.

prompt property

prompt: RenderableType

The prompt for the option.

set_prompt method

def set_prompt(self, prompt):

Set the prompt for the option.

Parameters
Parameter Default Description
prompt
RenderableType
required

The new prompt for the option.

OptionDoesNotExist class

Bases: Exception

Raised when a request has been made for an option that doesn't exist.

Separator class

Class used to add a separator to an OptionList.