Skip to content

Tutorial Themes

rafageist edited this page Dec 1, 2026 · 1 revision

Tutorial step 4: themes

Step 4 adds Options > Colors, which previews every theme as you move through them and keeps your choice for the next start. It adds a theme menu that switches at once, and a window of its own that paints itself with the theme's colour roles. (Step 3 comes first.)

python examples/tutorial/step4_themes.py

Options > Colors

Options > Colors previews every theme

The program, step4_themes.py:

# SPDX-License-Identifier: GPL-3.0-or-later
"""Step 4: themes. Options > Colors previews every theme as you move through them and keeps your choice; a
window of your own paints itself with the theme's colour roles, in its CSS ($tf-*) and in its code.

    python examples/tutorial/step4_themes.py
"""

from __future__ import annotations

from rich.text import Text
from textual.app import ComposeResult
from textual.widgets import Static
from textual_vision.constants import Command
from textual_vision.menus import Menu, MenuItem, Separator, SubMenu

from step2_windows import CM_CASCADE, CM_NEXT, CM_TILE
from step3_dialogs import CM_ABOUT, CM_FIND, CM_OPEN, CM_RENAME, Dialogs, JsonStore
from turboframe.ui import themes
from turboframe.ui.windows import TVWindow

CM_COLORS = Command.USER + 20
CM_ROLES = Command.USER + 21
CM_THEME = Command.USER + 100  # + the theme's index: Options > Theme
THEME_NAMES = list(themes.THEMES)


class Roles(Static):
    """Some of the theme's colour roles, painted from code: themes.current() is the theme on screen."""

    DEFAULT_CSS = "Roles { background: $tf-editor-bg; color: $tf-editor-text; padding: 0 1; }"

    def render(self) -> Text:
        palette = themes.current()
        text = Text(f"{palette.name}\n\n")
        for role in ("desktop", "editor-bg", "output-bg", "help-bg", "progress-fill", "shadow"):
            text.append("[")
            text.append("      ", style=f"on {palette.colour(role)}")  # a swatch: the role's colour as a background
            text.append(f"]  {role}\n")
        return text


class RolesWindow(TVWindow):
    def compose_content(self) -> ComposeResult:
        yield Roles()


class Themes(Dialogs):
    TITLE = "Themes"

    def __init__(self, store=None) -> None:
        store = store or JsonStore(self.STORE)
        self.colors_store = store  # Options > Colors keeps "palette" and "colors" here; the next start uses them
        super().__init__(store)

    def init_menu_bar(self) -> Menu:
        return Menu([
            SubMenu("~F~ile", MenuItem("~O~pen...", CM_OPEN, "F3"), MenuItem("~R~ename window...", CM_RENAME),
                    Separator(), MenuItem("E~x~it", Command.QUIT, "Alt+X")),
            SubMenu("~E~dit", MenuItem("~F~ind...", CM_FIND, "Ctrl+F")),
            SubMenu("~O~ptions", MenuItem("~C~olors...", CM_COLORS), Separator(),
                    *(MenuItem(themes.get(name).label.replace("~", ""), CM_THEME + i)
                      for i, name in enumerate(THEME_NAMES))),
            SubMenu("~W~indow", MenuItem("~R~oles", CM_ROLES), MenuItem("~T~ile", CM_TILE),
                    MenuItem("C~a~scade", CM_CASCADE), MenuItem("~N~ext", CM_NEXT, "F6")),
            SubMenu("~H~elp", MenuItem("~A~bout...", CM_ABOUT)),
        ])

    def start(self) -> None:
        self.show_roles()

    def handle(self, command: int) -> bool:
        if command == CM_COLORS:
            self.run_worker(self.choose_colors())  # ColorsMixin, part of DesktopApp
        elif command == CM_ROLES:
            self.show_roles()
        elif CM_THEME <= command < CM_THEME + len(THEME_NAMES):
            self.theme = THEME_NAMES[command - CM_THEME]  # everything repaints: the CSS and what code paints
        else:
            return super().handle(command)
        return True

    def show_roles(self) -> None:
        self.insert_window(RolesWindow("Roles", number=self.free_number()))


if __name__ == "__main__":
    Themes().run()

The theme, and keeping it

self.theme = name switches the whole application: every widget's CSS, and what code paints, because DesktopApp.watch_theme calls themes.use(name) and repaints. The names are themes.THEMES' keys: turbo-pascal, turbo-c, free-pascal, modern-dark, and the phosphor screens.

colors_store is where Options > Colors keeps palette (the theme) and colors (the colour depth). DesktopApp reads both when it starts. It is set before super().__init__(), because the start-up reads it.

Turbo Pascal Free Pascal Modern dark
turbo-pascal free-pascal modern-dark
Phosphor amber Phosphor green
phosphor-amber phosphor-green

Colour roles

A theme is more than Textual's colours: it names roles, such as desktop, editor-bg, list-focused, progress-fill and shadow. Every theme gives each role a colour. Use them in two places:

  • In CSS, as $tf-<role>: Roles { background: $tf-editor-bg; }.
  • In code, with themes.current().colour(role): what Roles.render paints.

Then your widgets follow every theme, the monochrome ones included. See Themes and Colors for the roles, the colour depth, your own token kinds, and shadows.

Next: Step 5: tasks.

Clone this wiki locally