Python TUI framework with mouse support, modular widget system, customizable and rapid terminal markup language and more
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
PyTermGUI provides comprehensive color management and a powerful markup language (TIM - Terminal Inline Markup) for rich text formatting. The system supports RGB, HEX, indexed terminal colors, and palette generation.
PyTermGUI's color system provides full support for terminal colors including RGB, HEX, indexed colors, and automatic terminal compatibility.
class Color:
"""Base color class with terminal conversion."""
def __init__(self, value: str | int | tuple):
"""
Create color from various formats.
Parameters:
- value: Color specification (hex string, RGB tuple, color name, etc.)
"""
@property
def rgb(self) -> tuple[int, int, int]:
"""Get RGB values as (r, g, b) tuple."""
def hex(self) -> str:
"""Get hexadecimal color representation."""
def __str__(self) -> str:
"""Get ANSI escape sequence for foreground."""
def as_background(self) -> str:
"""Get ANSI escape sequence for background."""
class RGBColor(Color):
"""True RGB color support."""
def __init__(self, red: int, green: int, blue: int):
"""
Create RGB color.
Parameters:
- red (int): Red component (0-255)
- green (int): Green component (0-255)
- blue (int): Blue component (0-255)
"""
class HEXColor(RGBColor):
"""Hexadecimal color support."""
def __init__(self, hex_value: str):
"""
Create color from hex string.
Parameters:
- hex_value (str): Hex color code ('#FF0000' or 'FF0000')
"""
class IndexedColor(Color):
"""256-color indexed terminal colors."""
def __init__(self, index: int):
"""
Create indexed color.
Parameters:
- index (int): Color index (0-255)
"""
class StandardColor(IndexedColor):
"""Standard 16-color terminal colors."""
class GreyscaleRampColor(IndexedColor):
"""Greyscale color ramp."""Helper functions for color parsing and text formatting.
def str_to_color(color_str: str) -> Color:
"""
Parse color string into Color object.
Parameters:
- color_str (str): Color specification (name, hex, rgb, etc.)
Returns:
Color object
Supports formats:
- Named colors: 'red', 'blue', 'green'
- Hex colors: '#FF0000', 'ff0000'
- RGB tuples: '(255, 0, 0)'
- Indexed colors: '196', '@196'
"""
def foreground(text: str, color: str | Color, reset: bool = True) -> str:
"""
Apply foreground color to text.
Parameters:
- text (str): Text to colorize
- color: Color specification
- reset (bool): Whether to add reset sequence
Returns:
Colored text with ANSI sequences
"""
def background(text: str, color: str | Color, reset: bool = True) -> str:
"""
Apply background color to text.
Parameters:
- text (str): Text to colorize
- color: Color specification
- reset (bool): Whether to add reset sequence
Returns:
Text with background color ANSI sequences
"""
def clear_color_cache() -> None:
"""Clear color conversion cache."""Color palette generation and management for cohesive color schemes.
class Palette:
"""Color palette management."""
def __init__(self, **colors):
"""
Create color palette.
Parameters:
- colors: Named color mappings
"""
def __getitem__(self, key: str) -> Color:
"""Get color by name."""
def set(self, key: str, color: Color):
"""Set named color."""
def triadic(base: Color) -> tuple[Color, Color, Color, Color]:
"""
Generate triadic color scheme.
Parameters:
- base (Color): Base color for scheme
Returns:
Tuple of (base, complement1, complement2, accent)
"""
def analogous(base: Color) -> tuple[Color, Color, Color, Color]:
"""
Generate analogous color scheme.
Parameters:
- base (Color): Base color for scheme
Returns:
Tuple of related colors
"""
# Global palette instance
palette: PaletteTerminal Inline Markup (TIM) provides rich text formatting with colors, styles, and layout control.
class MarkupLanguage:
"""TIM markup parser and processor."""
def __init__(self):
"""Initialize markup language processor."""
def parse(self, text: str) -> list[Token]:
"""
Parse markup text into tokens.
Parameters:
- text (str): Text with TIM markup
Returns:
List of parsed tokens
"""
def apply(self, text: str, **context) -> str:
"""
Apply markup formatting to text.
Parameters:
- text (str): Text with markup
- context: Markup context variables
Returns:
Formatted text with ANSI sequences
"""
class StyledText:
"""Styled text representation."""
def __init__(self, text: str):
"""
Create styled text.
Parameters:
- text (str): Text with markup
"""
def __str__(self) -> str:
"""Get formatted text output."""
@property
def plain(self) -> str:
"""Get plain text without formatting."""
def escape(text: str) -> str:
"""
Escape TIM markup characters in text.
Parameters:
- text (str): Text to escape
Returns:
Text with escaped markup characters
"""
# Global TIM instance
tim: MarkupLanguageToken classes representing different markup elements.
class Token:
"""Base markup token."""
def apply(self, text: str) -> str:
"""Apply token formatting."""
class PlainToken(Token):
"""Plain text token."""
class StyleToken(Token):
"""Style application token (bold, italic, etc.)."""
class ColorToken(Token):
"""Color application token."""
class ResetToken(Token):
"""Style reset token."""
class ClearScreenToken(Token):
"""Screen clear token."""Low-level markup parsing utilities.
def tokenize_markup(text: str) -> list[Token]:
"""
Tokenize markup text.
Parameters:
- text (str): Text with TIM markup
Returns:
List of markup tokens
"""
def tokenize_ansi(text: str) -> list[Token]:
"""
Tokenize ANSI escape sequences.
Parameters:
- text (str): Text with ANSI sequences
Returns:
List of ANSI tokens
"""
def consume_tag(text: str, pos: int) -> tuple[Token, int]:
"""
Parse single markup tag.
Parameters:
- text (str): Source text
- pos (int): Current position
Returns:
Tuple of (token, new_position)
"""
def create_context_dict(**kwargs) -> dict:
"""Create markup context dictionary."""
type ContextDict = dict[str, Any]# Pre-defined color lookup tables
COLOR_TABLE: dict[int, tuple[int, int, int]]
XTERM_NAMED_COLORS: dict[str, int]
NAMED_COLORS: dict[str, str]import pytermgui as ptg
# Create colors different ways
red = ptg.Color('red')
blue = ptg.HEXColor('#0066CC')
green = ptg.RGBColor(0, 255, 0)
# Apply colors to text
colored_text = ptg.foreground("Hello", red)
bg_text = ptg.background("World", blue)
print(colored_text, bg_text)import pytermgui as ptg
# Basic markup formatting
markup_text = "[bold red]Error:[/red bold] Something went wrong"
formatted = ptg.tim.parse(markup_text)
# Widget with markup
label = ptg.Label("[210 bold]Welcome to [/bold][157]PyTermGUI[/157]")
# Complex markup with colors and styles
title = ptg.Label("""
[bold 210]╔══════════════════╗
[bold 210]║ [/210][bold 157]Application Title[/157][bold 210] ║
[bold 210]╚══════════════════╝[/210 bold]
""")import pytermgui as ptg
# Generate color schemes
base_color = ptg.Color('#3366CC')
triadic_colors = ptg.triadic(base_color)
analogous_colors = ptg.analogous(base_color)
# Create custom palette
my_palette = ptg.Palette(
primary='#3366CC',
secondary='#66CC33',
accent='#CC3366',
background='#2D2D2D',
text='#FFFFFF'
)
# Use palette colors
button = ptg.Button(
f"[{my_palette['primary']}]Click Me[/]",
onclick=my_handler
)import pytermgui as ptg
# Strip formatting
plain_text = ptg.strip_markup("[bold red]Hello[/red bold]")
no_ansi = ptg.strip_ansi("\033[1;31mHello\033[0m")
# Measure display width
display_width = ptg.real_length("[bold]Hello World[/bold]")
# Escape markup characters
safe_text = ptg.escape("Text with [brackets] and /slashes/")Install with Tessl CLI
npx tessl i tessl/pypi-pytermgui