[go: up one dir, main page]

Skip to content

Tabs

Added in version 0.15.0

Displays a number of tab headers which may be activated with a click or navigated with cursor keys.

  • Focusable
  • Container

Construct a Tabs widget with strings or Text objects as positional arguments, which will set the labels in the tabs. Here's an example with three tabs:

def compose(self) -> ComposeResult:
    yield Tabs("First tab", "Second tab", Text.from_markup("[u]Third[/u] tab"))

This will create Tab widgets internally, with auto-incrementing id attributes ("tab-1", "tab-2" etc). You can also supply Tab objects directly in the constructor, which will allow you to explicitly set an id. Here's an example:

def compose(self) -> ComposeResult:
    yield Tabs(
        Tab("First tab", id="one"),
        Tab("Second tab", id="two"),
    )

When the user switches to a tab by clicking or pressing keys, then Tabs will send a Tabs.TabActivated message which contains the tab that was activated. You can then use event.tab.id attribute to perform any related actions.

Clearing tabs

Clear tabs by calling the clear method. Clearing the tabs will send a Tabs.TabActivated message with the tab attribute set to None.

Adding tabs

Tabs may be added dynamically with the add_tab method, which accepts strings, Text, or Tab objects.

Example

The following example adds a Tabs widget above a text label. Press A to add a tab, C to clear the tabs.

TabsApp ul AtreidiesDuke Leto AtreidesLady JessicaGurney HalleckBaron Vladimir H ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ Lady Jessica ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁  a Add tab  r Remove active tab  c Clear tabs ^p palette

from textual.app import App, ComposeResult
from textual.widgets import Footer, Label, Tabs

NAMES = [
    "Paul Atreidies",
    "Duke Leto Atreides",
    "Lady Jessica",
    "Gurney Halleck",
    "Baron Vladimir Harkonnen",
    "Glossu Rabban",
    "Chani",
    "Silgar",
]


class TabsApp(App):
    """Demonstrates the Tabs widget."""

    CSS = """
    Tabs {
        dock: top;
    }
    Screen {
        align: center middle;
    }
    Label {
        margin:1 1;
        width: 100%;
        height: 100%;
        background: $panel;
        border: tall $primary;
        content-align: center middle;
    }
    """

    BINDINGS = [
        ("a", "add", "Add tab"),
        ("r", "remove", "Remove active tab"),
        ("c", "clear", "Clear tabs"),
    ]

    def compose(self) -> ComposeResult:
        yield Tabs(NAMES[0])
        yield Label()
        yield Footer()

    def on_mount(self) -> None:
        """Focus the tabs when the app starts."""
        self.query_one(Tabs).focus()

    def on_tabs_tab_activated(self, event: Tabs.TabActivated) -> None:
        """Handle TabActivated message sent by Tabs."""
        label = self.query_one(Label)
        if event.tab is None:
            # When the tabs are cleared, event.tab will be None
            label.visible = False
        else:
            label.visible = True
            label.update(event.tab.label)

    def action_add(self) -> None:
        """Add a new tab."""
        tabs = self.query_one(Tabs)
        # Cycle the names
        NAMES[:] = [*NAMES[1:], NAMES[0]]
        tabs.add_tab(NAMES[0])

    def action_remove(self) -> None:
        """Remove active tab."""
        tabs = self.query_one(Tabs)
        active_tab = tabs.active_tab
        if active_tab is not None:
            tabs.remove_tab(active_tab.id)

    def action_clear(self) -> None:
        """Clear the tabs."""
        self.query_one(Tabs).clear()


if __name__ == "__main__":
    app = TabsApp()
    app.run()

Reactive Attributes

Name Type Default Description
active str "" The ID of the active tab. Set this attribute to a tab ID to change the active tab.

Messages

Bindings

The Tabs widget defines the following bindings:

Key(s) Description
left Move to the previous tab.
right Move to the next tab.

Component Classes

This widget has no component classes.


Bases: Widget

A row of tabs.

Parameters:

Name Type Description Default

*tabs

Tab | TextType

Positional argument should be explicit Tab objects, or a str or Text.

()

active

str | None

ID of the tab which should be active on start.

None

name

str | None

Optional name for the tabs widget.

None

id

str | None

Optional ID for the widget.

None

classes

str | None

Optional initial classes for the widget.

None

disabled

bool

Whether the widget is disabled or not.

False

BINDINGS class-attribute

BINDINGS = [
    Binding(
        "left", "previous_tab", "Previous tab", show=False
    ),
    Binding("right", "next_tab", "Next tab", show=False),
]
Key(s) Description
left Move to the previous tab.
right Move to the next tab.

active class-attribute instance-attribute

active = reactive('', init=False)

The ID of the active tab, or empty string if none are active.

active_tab property

active_tab

The currently active tab, or None if there are no active tabs.

tab_count property

tab_count

Total number of tabs.

Cleared

Cleared(tabs)

Bases: Message

Sent when there are no active tabs.

This can occur when Tabs are cleared, if all tabs are hidden, or if the currently active tab is unset.

Parameters:

Name Type Description Default

tabs

Tabs

The tabs widget.

required

control property

control

The tabs widget which was cleared.

This is an alias for Cleared.tabs which is used by the on decorator.

tabs instance-attribute

tabs = tabs

The tabs widget which was cleared.

TabActivated

TabActivated(tabs, tab)

Bases: TabMessage

Sent when a new tab is activated.

Parameters:

Name Type Description Default

tabs

Tabs

The Tabs widget.

required

tab

Tab

The tab that is the object of this message.

required

TabDisabled

TabDisabled(tabs, tab)

Bases: TabMessage

Sent when a tab is disabled.

Parameters:

Name Type Description Default

tabs

Tabs

The Tabs widget.

required

tab

Tab

The tab that is the object of this message.

required

TabEnabled

TabEnabled(tabs, tab)

Bases: TabMessage

Sent when a tab is enabled.

Parameters:

Name Type Description Default

tabs

Tabs

The Tabs widget.

required

tab

Tab

The tab that is the object of this message.

required

TabError

Bases: Exception

Exception raised when there is an error relating to tabs.

TabHidden

TabHidden(tabs, tab)

Bases: TabMessage

Sent when a tab is hidden.

Parameters:

Name Type Description Default

tabs

Tabs

The Tabs widget.

required

tab

Tab

The tab that is the object of this message.

required

TabMessage

TabMessage(tabs, tab)

Bases: Message

Parent class for all messages that have to do with a specific tab.

Parameters:

Name Type Description Default

tabs

Tabs

The Tabs widget.

required

tab

Tab

The tab that is the object of this message.

required

ALLOW_SELECTOR_MATCH class-attribute instance-attribute

ALLOW_SELECTOR_MATCH = {'tab'}

Additional message attributes that can be used with the on decorator.

control property

control

The tabs widget containing the tab that is the object of this message.

This is an alias for the attribute tabs and is used by the on decorator.

tab instance-attribute

tab = tab

The tab that is the object of this message.

tabs instance-attribute

tabs = tabs

The tabs widget containing the tab.

TabShown

TabShown(tabs, tab)

Bases: TabMessage

Sent when a tab is shown.

Parameters:

Name Type Description Default

tabs

Tabs

The Tabs widget.

required

tab

Tab

The tab that is the object of this message.

required

action_next_tab

action_next_tab()

Make the next tab active.

action_previous_tab

action_previous_tab()

Make the previous tab active.

add_tab

add_tab(tab, *, before=None, after=None)

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

Parameters:

Name Type Description Default

tab

Tab | str | Text

A new tab object, or a label (str or Text).

required

before

Tab | str | None

Optional tab or tab ID to add the tab before.

None

after

Tab | str | None

Optional tab or tab ID to add the tab after.

None

Returns:

Type Description
AwaitComplete

An optionally awaitable object that waits for the tab to be mounted and internal state to be fully updated to reflect the new tab.

Raises:

Type Description
TabError

If there is a problem with the addition request.

Note

Only one of before or after can be provided. If both are provided a Tabs.TabError will be raised.

clear

clear()

Clear all the tabs.

Returns:

Type Description
AwaitComplete

An awaitable object that waits for the tabs to be removed.

disable

disable(tab_id)

Disable the indicated tab.

Parameters:

Name Type Description Default

tab_id

str

The ID of the Tab to disable.

required

Returns:

Type Description
Tab

The Tab that was targeted.

Raises:

Type Description
TabError

If there are any issues with the request.

enable

enable(tab_id)

Enable the indicated tab.

Parameters:

Name Type Description Default

tab_id

str

The ID of the Tab to enable.

required

Returns:

Type Description
Tab

The Tab that was targeted.

Raises:

Type Description
TabError

If there are any issues with the request.

hide

hide(tab_id)

Hide the indicated tab.

Parameters:

Name Type Description Default

tab_id

str

The ID of the Tab to hide.

required

Returns:

Type Description
Tab

The Tab that was targeted.

Raises:

Type Description
TabError

If there are any issues with the request.

remove_tab

remove_tab(tab_or_id)

Remove a tab.

Parameters:

Name Type Description Default

tab_or_id

Tab | str | None

The Tab to remove or its id.

required

Returns:

Type Description
AwaitComplete

An optionally awaitable object that waits for the tab to be removed.

show

show(tab_id)

Show the indicated tab.

Parameters:

Name Type Description Default

tab_id

str

The ID of the Tab to show.

required

Returns:

Type Description
Tab

The Tab that was targeted.

Raises:

Type Description
TabError

If there are any issues with the request.

validate_active

validate_active(active)

Check id assigned to active attribute is a valid tab.

watch_active

watch_active(previously_active, active)

Handle a change to the active tab.


Bases: Static

A Widget to manage a single tab within a Tabs widget.

Parameters:

Name Type Description Default

label

TextType

The label to use in the tab.

required

id

str | None

Optional ID for the widget.

None

classes

str | None

Space separated list of class names.

None

disabled

bool

Whether the tab is disabled or not.

False

label property writable

label

The label for the tab.

label_text property

label_text

Undecorated text of the label.

Clicked dataclass

Clicked(tab)

Bases: TabMessage

A tab was clicked.

Disabled dataclass

Disabled(tab)

Bases: TabMessage

A tab was disabled.

Enabled dataclass

Enabled(tab)

Bases: TabMessage

A tab was enabled.

Relabelled dataclass

Relabelled(tab)

Bases: TabMessage

A tab was relabelled.

TabMessage dataclass

TabMessage(tab)

Bases: Message

Tab-related messages.

These are mostly intended for internal use when interacting with Tabs.

control property

control

The tab that is the object of this message.

This is an alias for the attribute tab and is used by the on decorator.

tab instance-attribute

tab

The tab that is the object of this message.