CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pytermgui

Python TUI framework with mouse support, modular widget system, customizable and rapid terminal markup language and more

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

window-management.mddocs/

Window Management

PyTermGUI's window management system provides desktop-like window functionality with multi-window support, compositing, event routing, and flexible layout management. The system enables complex applications with overlapping windows and sophisticated user interfaces.

Capabilities

WindowManager

Central manager for multiple windows, handling input routing, focus management, and application lifecycle.

class WindowManager:
    """Multi-window application manager."""
    
    def __init__(self, *, layout_type: type = None, framerate: int = 60, 
                 autorun: bool = None):
        """
        Initialize window manager.
        
        Parameters:
        - layout_type (type, optional): Layout class to use
        - framerate (int): Target framerate, defaults to 60
        - autorun (bool, optional): Whether to auto-run, defaults to class setting
        """
    
    def add(self, window: "Window", assign: str | bool = True, 
            animate: bool = True) -> "WindowManager":
        """
        Add window to manager.
        
        Parameters:
        - window (Window): Window to add
        - assign (str | bool): Layout assignment - slot name, True for auto, or False for none
        - animate (bool): Whether to animate window addition
        
        Returns:
        The WindowManager instance for chaining
        """
    
    def remove(self, window: "Window") -> "Window":
        """Remove window from manager."""
    
    def focus(self, window: "Window"):
        """Set window focus."""
    
    def run(self):
        """Start window manager event loop."""
    
    def stop(self):
        """Stop window manager and exit event loop."""
    
    @property
    def focused(self) -> "Window | None":
        """Get currently focused window."""
    
    @property
    def windows(self) -> list["Window"]:
        """Get list of managed windows."""
    
    def screenshot(self) -> str:
        """Capture screenshot of all windows."""

Window

Desktop-style window widget extending Container with title bar, borders, and window controls.

class Window(Container):
    """Desktop-style window widget."""
    
    def __init__(self, *widgets, title: str = "", **attrs):
        """
        Create window widget.
        
        Parameters:
        - widgets: Child widgets for window content
        - title (str): Window title text
        - is_modal (bool, optional): Whether window is modal
        - is_noblur (bool, optional): Whether window stays in focus
        - is_noresize (bool, optional): Whether window can be resized
        """
    
    @property
    def title(self) -> str:
        """Get window title."""
    
    @title.setter
    def title(self, value: str):
        """Set window title."""
    
    def close(self):
        """Close window."""
    
    def minimize(self):
        """Minimize window."""
    
    def maximize(self):
        """Maximize window."""
    
    def center(self, where: CenteringPolicy = None):
        """Center window on screen."""
    
    def move(self, pos: tuple[int, int]):
        """Move window to position."""
    
    def resize(self, size: tuple[int, int]):
        """Resize window."""

Compositor

Efficient window rendering system that handles overlapping windows, damage tracking, and optimized screen updates.

class Compositor:
    """Window compositing and rendering system."""
    
    def __init__(self):
        """Initialize compositor."""
    
    def render(self):
        """Render all windows to screen."""
    
    def damage(self, window: Window):
        """Mark window as needing redraw."""
    
    def set_target_fps(self, fps: int):
        """Set target framerate for rendering."""
    
    @property
    def fps(self) -> float:
        """Get current rendering framerate."""

Layout Management

Window layout system for organizing windows in predefined arrangements.

class Layout:
    """Window layout management."""
    
    def __init__(self, name: str):
        """
        Create layout configuration.
        
        Parameters:
        - name (str): Layout identifier
        """
    
    def apply(self, manager: WindowManager):
        """Apply layout to window manager."""
    
    def add_slot(self, name: str, area: tuple[int, int, int, int]):
        """
        Add layout slot.
        
        Parameters:
        - name (str): Slot identifier
        - area (tuple): (x, y, width, height) area definition
        """

Usage Examples

Basic Window Application

import pytermgui as ptg

def main():
    # Create window manager
    with ptg.WindowManager() as manager:
        # Create main window
        window = ptg.Window(
            "[bold]Welcome to PyTermGUI",
            "",
            ptg.Label("This is a window with content"),
            ptg.Button("Click me", lambda btn: print("Clicked!")),
            "",
            ptg.Button("Exit", lambda btn: manager.stop()),
            title="My Application",
            width=50,
            height=15
        )
        
        # Add window to manager
        manager.add(window)
        
        # Start event loop
        # This will block until manager.stop() is called

if __name__ == "__main__":
    main()

Multi-Window Application

import pytermgui as ptg

def create_settings_window(manager):
    """Create settings dialog."""
    settings = ptg.Window(
        "[bold]Settings",
        "",
        ptg.Splitter(
            ptg.Label("Theme:"),
            ptg.Toggle(("Dark", "Light"))
        ),
        ptg.Splitter(
            ptg.Label("Sound:"),
            ptg.Checkbox(checked=True)
        ),
        "",
        ptg.Button("OK", lambda btn: settings.close()),
        title="Settings",
        width=40,
        height=10
    )
    return settings

def main():
    with ptg.WindowManager() as manager:
        # Main application window
        main_window = ptg.Window(
            "[bold]Main Application",
            "",
            ptg.Button("Open Settings", 
                      lambda btn: manager.add(create_settings_window(manager))),
            ptg.Button("Exit", lambda btn: manager.stop()),
            title="App",
            width=60,
            height=20
        )
        
        manager.add(main_window)

if __name__ == "__main__":
    main()

Modal Dialog

import pytermgui as ptg

def show_confirmation(manager, message, callback):
    """Show modal confirmation dialog."""
    def on_yes(btn):
        dialog.close()
        callback(True)
    
    def on_no(btn):
        dialog.close() 
        callback(False)
    
    dialog = ptg.Window(
        f"[bold]{message}",
        "",
        ptg.Splitter(
            ptg.Button("Yes", on_yes),
            ptg.Button("No", on_no)
        ),
        title="Confirm",
        is_modal=True,  # Modal window
        width=40,
        height=8
    )
    
    manager.add(dialog)
    dialog.center()  # Center on screen

# Usage
def handle_delete():
    show_confirmation(
        manager, 
        "Delete this item?",
        lambda result: print(f"User selected: {result}")
    )

Window with Custom Layout

import pytermgui as ptg

def create_dashboard():
    """Create dashboard with multiple panels."""
    
    # Create layout panels as separate containers
    left_panel = ptg.Container(
        "[bold]Navigation",
        "",
        ptg.Button("Home", lambda: switch_view("home")),
        ptg.Button("Settings", lambda: switch_view("settings")),
        ptg.Button("About", lambda: switch_view("about")),
        width=20
    )
    
    main_panel = ptg.Container(
        "[bold]Main Content",
        "",
        ptg.Label("Welcome to the dashboard"),
        ptg.Label("Select an option from the navigation"),
        width=50
    )
    
    # Combine panels horizontally
    layout = ptg.Splitter(left_panel, main_panel)
    
    window = ptg.Window(
        layout,
        title="Dashboard",
        width=75,
        height=25
    )
    
    return window

with ptg.WindowManager() as manager:
    dashboard = create_dashboard()
    manager.add(dashboard)

Context Manager Usage

import pytermgui as ptg

# WindowManager as context manager automatically handles cleanup
with ptg.WindowManager() as manager:
    # Create and add windows
    window = ptg.Window("Content", title="Auto-managed")
    manager.add(window)
    
    # Event loop runs here
    # Cleanup happens automatically when exiting context

Window Events and Callbacks

import pytermgui as ptg

def on_window_close(window):
    """Handle window close event."""
    print(f"Window '{window.title}' is closing")
    
def on_window_focus(window):
    """Handle window focus event."""
    print(f"Window '{window.title}' gained focus")

# Create window with event handlers
window = ptg.Window(
    "Content",
    title="Event Demo",
    on_close=on_window_close,
    on_focus=on_window_focus
)

Install with Tessl CLI

npx tessl i tessl/pypi-pytermgui

docs

animations.md

colors-markup.md

file-loading.md

index.md

terminal.md

utilities.md

widgets.md

window-management.md

tile.json