Skip to content

Panel Reference

Bases: Gradient

A Rich Panel whose border, title, and content share one gradient.

Parameters:

Name Type Description Default
renderable RenderableType

Content of the panel. Strings are parsed as console markup, e.g. "Hello, [b]panel[/b]!".

required
colors Optional[list[ColorType]]

Foreground color stops. Each stop may be a color name (Rich/ANSI names such as "red" keep Rich's meaning; CSS names such as "tomato" also work), a hex string ("#f00", "#ff0000"), an "rgb(255, 0, 0)" string, an (r, g, b) tuple, or a rich.color.Color, e.g. ["#f00", "orange", (0, 128, 255)]. If omitted and rainbow is False, hues colors are taken from the spectrum palette. Defaults to None.

None
bg_colors Optional[list[ColorType]]

Background color stops, in the same formats as colors, e.g. ["#000033", "#330033"]. If omitted, no background gradient is applied. Defaults to None.

None
rainbow bool

Use the full 17-color spectrum palette, ignoring colors and hues. Defaults to False.

False
hues int

Number of colors to take from the spectrum palette when colors is omitted (a run of consecutive hues with a random starting point). Valid values are 2 to 17. Defaults to 5.

5
title Optional[TextType]

Title shown in the top border of the panel: a string (parsed as console markup) or a Text. Defaults to None.

None
title_align AlignMethod

Alignment of the title: "left", "center", or "right". Defaults to "center".

'center'
title_style StyleType

Style layered over the gradient on the title text. A style string or rich.style.Style, e.g. "dim italic". Unlike style, a color here is shown, drawn on top of the gradient. Defaults to "bold".

'bold'
subtitle Optional[TextType]

Subtitle shown in the bottom border of the panel: a string (parsed as console markup) or a Text. Defaults to None.

None
subtitle_align AlignMethod

Alignment of the subtitle: "left", "center", or "right". Defaults to "right".

'right'
subtitle_style StyleType

Style layered over the gradient on the subtitle text. A style string or rich.style.Style, e.g. "dim italic". Unlike style, a color here is shown, drawn on top of the gradient. Defaults to "".

''
border_style StyleType

Style of the border, under the gradient. A style string or rich.style.Style, e.g. "dim italic". A foreground color in this style is replaced by the gradient; a background color is kept unless bg_colors is set. Defaults to "".

''
justify AlignMethod

Horizontal alignment of the panel: "left", "center", or "right". Defaults to "left".

'left'
vertical_justify VerticalAlignMethod

Vertical alignment of the panel: "top", "middle", or "bottom". Defaults to "middle".

'middle'
box Box

Box characters for the border, any rich.box constant, e.g. rich.box.HEAVY or rich.box.DOUBLE. Defaults to rich.box.ROUNDED.

ROUNDED
padding int | tuple[int, int] | tuple[int, int, int, int]

Padding inside the border, CSS-style: 1 (all sides), (top_bottom, left_right), or (top, right, bottom, left), e.g. (1, 2). Defaults to (0, 1, 0, 1).

(0, 1, 0, 1)
expand bool

Expand the output to the full available width. Defaults to True.

True
text_justify AlignMethod

Alignment of the text inside the panel (string content only): "left", "center", or "right". Defaults to "left".

'left'
style StyleType

Base style of the panel content. A style string or rich.style.Style, e.g. "dim italic". A foreground color in this style is replaced by the gradient (a background color is kept unless bg_colors is set); with border_only, colors here are shown as in a plain Rich panel. Defaults to "".

''
width Optional[int]

Fixed width in cells, or None to size automatically. Defaults to None.

None
height Optional[int]

Fixed height in lines, or None to size automatically. Defaults to None.

None
safe_box bool

Use box characters that render on legacy Windows terminals. Defaults to False.

False
highlight_words Optional[HighlightWordsType]

Words to restyle on top of the gradient. Accepts a mapping of a word (or a tuple of words) to a style, e.g. {"error": "bold red", ("warn", "caution"): "yellow"}; a sequence of (words, style[, case_sensitive]) tuples, e.g. [("error", "bold red"), (("warn", "caution"), "yellow", False)]; or HighlightWords instances, e.g. [HighlightWords(words=("error",), style=Style.parse("bold red"))]. Matching is case-sensitive unless case_sensitive is False. Colors in these styles are shown: they replace the gradient on the matched text. Defaults to None.

None
highlight_regex Optional[HighlightRegexType]

Regular expressions whose matches are restyled on top of the gradient. Accepts a mapping of a pattern to a style, e.g. {r"[0-9]+": "bold cyan"}; a sequence of (pattern, style[, flags]) tuples, e.g. [(r"error|fail", "red", re.IGNORECASE)]; or HighlightRegex instances, e.g. [HighlightRegex(pattern=re.compile(r"[0-9]+"), style=Style.parse("cyan"))]. Colors in these styles are shown: they replace the gradient on the matched text. Defaults to None.

None
animate bool

Mark the content as changing between renders, so highlight matches are recomputed every frame instead of cached. Static renderables never animate on their own; use the Animated* classes for live animation. Defaults to False.

False
border_only bool

Paint only the border with the gradient (its title and subtitle too, as Rich draws them in the border style) and draw the content exactly as a plain rich.panel.Panel would, keeping its own colors and background. Defaults to False.

False
Source code in src/rich_gradient/panel.py
class Panel(Gradient):
    """A Rich ``Panel`` whose border, title, and content share one gradient.

    Args:
        renderable (RenderableType): Content of the panel. Strings are parsed as console
            markup, e.g. ``"Hello, [b]panel[/b]!"``.
        colors (Optional[list[ColorType]]): Foreground color stops. Each stop may be a
            color name (Rich/ANSI names such as ``"red"`` keep Rich's meaning; CSS names
            such as ``"tomato"`` also work), a hex string (``"#f00"``, ``"#ff0000"``),
            an ``"rgb(255, 0, 0)"`` string, an ``(r, g, b)`` tuple, or a
            ``rich.color.Color``, e.g. ``["#f00", "orange", (0, 128, 255)]``. If omitted
            and ``rainbow`` is False, ``hues`` colors are taken from the spectrum
            palette. Defaults to None.
        bg_colors (Optional[list[ColorType]]): Background color stops, in the same
            formats as ``colors``, e.g. ``["#000033", "#330033"]``. If omitted, no
            background gradient is applied. Defaults to None.
        rainbow (bool): Use the full 17-color spectrum palette, ignoring ``colors`` and
            ``hues``. Defaults to False.
        hues (int): Number of colors to take from the spectrum palette when ``colors``
            is omitted (a run of consecutive hues with a random starting point). Valid
            values are 2 to 17. Defaults to 5.
        title (Optional[TextType]): Title shown in the top border of the panel: a string
            (parsed as console markup) or a ``Text``. Defaults to None.
        title_align (AlignMethod): Alignment of the title: ``"left"``, ``"center"``, or
            ``"right"``. Defaults to ``"center"``.
        title_style (StyleType): Style layered over the gradient on the title text. A
            style string or ``rich.style.Style``, e.g. ``"dim italic"``. Unlike
            ``style``, a color here is shown, drawn on top of the gradient. Defaults to
            ``"bold"``.
        subtitle (Optional[TextType]): Subtitle shown in the bottom border of the panel:
            a string (parsed as console markup) or a ``Text``. Defaults to None.
        subtitle_align (AlignMethod): Alignment of the subtitle: ``"left"``,
            ``"center"``, or ``"right"``. Defaults to ``"right"``.
        subtitle_style (StyleType): Style layered over the gradient on the subtitle
            text. A style string or ``rich.style.Style``, e.g. ``"dim italic"``. Unlike
            ``style``, a color here is shown, drawn on top of the gradient. Defaults to
            ``""``.
        border_style (StyleType): Style of the border, under the gradient. A style
            string or ``rich.style.Style``, e.g. ``"dim italic"``. A foreground color in
            this style is replaced by the gradient; a background color is kept unless
            ``bg_colors`` is set. Defaults to ``""``.
        justify (AlignMethod): Horizontal alignment of the panel: ``"left"``,
            ``"center"``, or ``"right"``. Defaults to ``"left"``.
        vertical_justify (VerticalAlignMethod): Vertical alignment of the panel:
            ``"top"``, ``"middle"``, or ``"bottom"``. Defaults to ``"middle"``.
        box (Box): Box characters for the border, any ``rich.box`` constant, e.g.
            ``rich.box.HEAVY`` or ``rich.box.DOUBLE``. Defaults to ``rich.box.ROUNDED``.
        padding (int | tuple[int, int] | tuple[int, int, int, int]): Padding inside the
            border, CSS-style: ``1`` (all sides), ``(top_bottom, left_right)``, or
            ``(top, right, bottom, left)``, e.g. ``(1, 2)``. Defaults to
            ``(0, 1, 0, 1)``.
        expand (bool): Expand the output to the full available width. Defaults to True.
        text_justify (AlignMethod): Alignment of the text inside the panel (string
            content only): ``"left"``, ``"center"``, or ``"right"``. Defaults to
            ``"left"``.
        style (StyleType): Base style of the panel content. A style string or
            ``rich.style.Style``, e.g. ``"dim italic"``. A foreground color in this
            style is replaced by the gradient (a background color is kept unless
            ``bg_colors`` is set); with ``border_only``, colors here are shown as in a
            plain Rich panel. Defaults to ``""``.
        width (Optional[int]): Fixed width in cells, or ``None`` to size automatically.
            Defaults to None.
        height (Optional[int]): Fixed height in lines, or ``None`` to size
            automatically. Defaults to None.
        safe_box (bool): Use box characters that render on legacy Windows terminals.
            Defaults to False.
        highlight_words (Optional[HighlightWordsType]): Words to restyle on top of the
            gradient. Accepts a mapping of a word (or a tuple of words) to a style, e.g.
            ``{"error": "bold red", ("warn", "caution"): "yellow"}``; a sequence of
            ``(words, style[, case_sensitive])`` tuples, e.g.
            ``[("error", "bold red"), (("warn", "caution"), "yellow", False)]``; or
            ``HighlightWords`` instances, e.g.
            ``[HighlightWords(words=("error",), style=Style.parse("bold red"))]``.
            Matching is case-sensitive unless ``case_sensitive`` is False. Colors in
            these styles are shown: they replace the gradient on the matched text.
            Defaults to None.
        highlight_regex (Optional[HighlightRegexType]): Regular expressions whose
            matches are restyled on top of the gradient. Accepts a mapping of a pattern
            to a style, e.g. ``{r"[0-9]+": "bold cyan"}``; a sequence of
            ``(pattern, style[, flags])`` tuples, e.g.
            ``[(r"error|fail", "red", re.IGNORECASE)]``; or ``HighlightRegex``
            instances, e.g.
            ``[HighlightRegex(pattern=re.compile(r"[0-9]+"), style=Style.parse("cyan"))]``.
            Colors in these styles are shown: they replace the gradient on the matched
            text. Defaults to None.
        animate (bool): Mark the content as changing between renders, so highlight
            matches are recomputed every frame instead of cached. Static renderables
            never animate on their own; use the ``Animated*`` classes for live
            animation. Defaults to False.
        border_only (bool): Paint only the border with the gradient (its title and
            subtitle too, as Rich draws them in the border style) and draw the content
            exactly as a plain ``rich.panel.Panel`` would, keeping its own colors and
            background. Defaults to False.
    """

    def __init__(
        self,
        renderable: RenderableType,
        colors: list[ColorType] | None = None,
        bg_colors: list[ColorType] | None = None,
        rainbow: bool = False,
        hues: int = 5,
        title: Text | RichText | TextType | None = None,
        title_align: AlignMethod = "center",
        title_style: StyleType = "bold",
        subtitle: Text | RichText | TextType | None = None,
        subtitle_align: AlignMethod = "right",
        subtitle_style: StyleType = "",
        border_style: StyleType = "",
        justify: AlignMethod = "left",
        vertical_justify: VerticalAlignMethod = "middle",
        box: Box = ROUNDED,
        padding: int | tuple[int, int] | tuple[int, int, int, int] = (0, 1, 0, 1),
        expand: bool = True,
        text_justify: AlignMethod = "left",
        style: StyleType = "",
        width: int | None = None,
        height: int | None = None,
        safe_box: bool = False,
        highlight_words: HighlightWordsType | None = None,
        highlight_regex: HighlightRegexType | None = None,
        *,
        animate: bool = False,
        border_only: bool = False,
    ) -> None:
        """Initialize the gradient panel; see the class docstring for arguments."""
        normalized_renderable = _normalize_panel_renderable(
            renderable, style=style, text_justify=text_justify
        )
        if isinstance(style, Style):
            _style = style
        else:
            _style = Style.parse(style) if style else Style.null()

        panel = _ExpandingRichPanel(
            normalized_renderable,
            title=title,
            title_align=title_align,
            subtitle=subtitle,
            subtitle_align=subtitle_align,
            border_style=border_style,
            box=box,
            padding=padding,
            expand=expand,
            style=_style,
            width=width,
            height=height,
            safe_box=safe_box,
        )

        # Track the underlying Rich Panel so expand setter can propagate to it
        # (Gradient.expand property will attempt to update ``self._panel``).
        self._panel: _ExpandingRichPanel = panel
        self.border_only = border_only

        # Highlight title and subtitle if they are provided
        ## Normalize highlight_regex into a mutable sequence of tuples (pattern, style, priority)
        highlight_list: list[tuple[str, StyleType, int]] = []
        if highlight_regex is None:
            pass
        elif isinstance(highlight_regex, Mapping):
            # Convert mapping to a list of (pattern, style, priority) tuples
            highlight_list = [
                (str(pattern), cast(StyleType, style), 0)
                for pattern, style in highlight_regex.items()
            ]
        else:
            # Assume it's already a sequence of tuples
            highlight_list = list(
                cast(Sequence[tuple[str, StyleType, int]], highlight_regex)
            )

        if title:
            title_regex = self._get_title_regex(box)
            highlight_list.append((title_regex, title_style or "bold", 0))
        if subtitle:
            subtitle_regex = self._get_subtitle_regex(box)
            highlight_list.append((subtitle_regex, subtitle_style or "", 0))

        super().__init__(
            panel,
            colors=colors,
            bg_colors=bg_colors,
            hues=hues,
            rainbow=rainbow,
            expand=expand,
            justify=justify,
            vertical_justify=vertical_justify,
            highlight_words=highlight_words,
            highlight_regex=highlight_list,
            animate=animate,
        )

    @staticmethod
    def _get_title_regex(box: Box) -> str:
        """Generate the regex used to highlight the title row.

        Args:
            box: The panel's box characters.

        Returns:
            A pattern capturing the title text in the top border.
        """
        top_left: str = escape(box.top_left)
        top: str = escape(box.top)
        top_right: str = escape(box.top_right)
        title_regex: str = rf"{top_left}{top}+ (.*?) {top}+{top_right}"
        return title_regex

    @staticmethod
    def _get_subtitle_regex(box: Box) -> str:
        """Generate the regex used to highlight the subtitle row.

        Args:
            box: The panel's box characters.

        Returns:
            A pattern capturing the subtitle text in the bottom border.
        """
        bottom_left: str = escape(box.bottom_left)
        bottom: str = escape(box.bottom)
        bottom_right: str = escape(box.bottom_right)
        subtitle_regex: str = rf"{bottom_left}{bottom}+ (.*?) {bottom}+{bottom_right}"
        return subtitle_regex

    def __rich_measure__(
        self, console: Console, options: ConsoleOptions
    ) -> Measurement:
        """Measure like a plain Rich ``Panel`` so parent layouts share width fairly.

        Args:
            console: The console used for measurement.
            options: The console options for the current render.

        Returns:
            The natural (non-expanded) width range of the panel.
        """
        return self._panel.natural_measure(console, options)

    @property
    def panel(self) -> RichPanel:
        """The underlying Rich Panel renderable."""
        return self._panel

    @property
    def border_only(self) -> bool:
        """Whether only the border (with its title and subtitle) takes the gradient."""
        return self._panel.mark_border

    @border_only.setter
    def border_only(self, value: bool) -> None:
        """Paint only the border with the gradient, or the whole panel.

        Args:
            value: ``True`` to leave the content as a plain Rich panel draws it.
        """
        self._panel.mark_border = bool(value)

    def _merge_styles(self, original: Style, gradient_style: Style) -> Style:
        """Merge the gradient into every cell, or only the border when ``border_only``.

        Args:
            original: The segment's style as Rich rendered it.
            gradient_style: The gradient color for the segment's position.

        Returns:
            The merged style; with ``border_only``, content cells keep ``original``.
        """
        if self.border_only:
            return _merge_border_only(original, gradient_style, super()._merge_styles)
        return super()._merge_styles(original, gradient_style)

border_only property writable

Whether only the border (with its title and subtitle) takes the gradient.

panel property

The underlying Rich Panel renderable.

__init__(renderable, colors=None, bg_colors=None, rainbow=False, hues=5, title=None, title_align='center', title_style='bold', subtitle=None, subtitle_align='right', subtitle_style='', border_style='', justify='left', vertical_justify='middle', box=ROUNDED, padding=(0, 1, 0, 1), expand=True, text_justify='left', style='', width=None, height=None, safe_box=False, highlight_words=None, highlight_regex=None, *, animate=False, border_only=False)

Initialize the gradient panel; see the class docstring for arguments.

Source code in src/rich_gradient/panel.py
def __init__(
    self,
    renderable: RenderableType,
    colors: list[ColorType] | None = None,
    bg_colors: list[ColorType] | None = None,
    rainbow: bool = False,
    hues: int = 5,
    title: Text | RichText | TextType | None = None,
    title_align: AlignMethod = "center",
    title_style: StyleType = "bold",
    subtitle: Text | RichText | TextType | None = None,
    subtitle_align: AlignMethod = "right",
    subtitle_style: StyleType = "",
    border_style: StyleType = "",
    justify: AlignMethod = "left",
    vertical_justify: VerticalAlignMethod = "middle",
    box: Box = ROUNDED,
    padding: int | tuple[int, int] | tuple[int, int, int, int] = (0, 1, 0, 1),
    expand: bool = True,
    text_justify: AlignMethod = "left",
    style: StyleType = "",
    width: int | None = None,
    height: int | None = None,
    safe_box: bool = False,
    highlight_words: HighlightWordsType | None = None,
    highlight_regex: HighlightRegexType | None = None,
    *,
    animate: bool = False,
    border_only: bool = False,
) -> None:
    """Initialize the gradient panel; see the class docstring for arguments."""
    normalized_renderable = _normalize_panel_renderable(
        renderable, style=style, text_justify=text_justify
    )
    if isinstance(style, Style):
        _style = style
    else:
        _style = Style.parse(style) if style else Style.null()

    panel = _ExpandingRichPanel(
        normalized_renderable,
        title=title,
        title_align=title_align,
        subtitle=subtitle,
        subtitle_align=subtitle_align,
        border_style=border_style,
        box=box,
        padding=padding,
        expand=expand,
        style=_style,
        width=width,
        height=height,
        safe_box=safe_box,
    )

    # Track the underlying Rich Panel so expand setter can propagate to it
    # (Gradient.expand property will attempt to update ``self._panel``).
    self._panel: _ExpandingRichPanel = panel
    self.border_only = border_only

    # Highlight title and subtitle if they are provided
    ## Normalize highlight_regex into a mutable sequence of tuples (pattern, style, priority)
    highlight_list: list[tuple[str, StyleType, int]] = []
    if highlight_regex is None:
        pass
    elif isinstance(highlight_regex, Mapping):
        # Convert mapping to a list of (pattern, style, priority) tuples
        highlight_list = [
            (str(pattern), cast(StyleType, style), 0)
            for pattern, style in highlight_regex.items()
        ]
    else:
        # Assume it's already a sequence of tuples
        highlight_list = list(
            cast(Sequence[tuple[str, StyleType, int]], highlight_regex)
        )

    if title:
        title_regex = self._get_title_regex(box)
        highlight_list.append((title_regex, title_style or "bold", 0))
    if subtitle:
        subtitle_regex = self._get_subtitle_regex(box)
        highlight_list.append((subtitle_regex, subtitle_style or "", 0))

    super().__init__(
        panel,
        colors=colors,
        bg_colors=bg_colors,
        hues=hues,
        rainbow=rainbow,
        expand=expand,
        justify=justify,
        vertical_justify=vertical_justify,
        highlight_words=highlight_words,
        highlight_regex=highlight_list,
        animate=animate,
    )

__rich_measure__(console, options)

Measure like a plain Rich Panel so parent layouts share width fairly.

Parameters:

Name Type Description Default
console Console

The console used for measurement.

required
options ConsoleOptions

The console options for the current render.

required

Returns:

Type Description
Measurement

The natural (non-expanded) width range of the panel.

Source code in src/rich_gradient/panel.py
def __rich_measure__(
    self, console: Console, options: ConsoleOptions
) -> Measurement:
    """Measure like a plain Rich ``Panel`` so parent layouts share width fairly.

    Args:
        console: The console used for measurement.
        options: The console options for the current render.

    Returns:
        The natural (non-expanded) width range of the panel.
    """
    return self._panel.natural_measure(console, options)