CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-brython

Python-to-JavaScript transpiler that enables Python 3 development in web browsers with full DOM integration and standard library support

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

ui-framework.mddocs/

UI Framework

Widget-based GUI toolkit with layout management, styling, and event handling for creating desktop-like web applications using Python. The UI framework provides high-level components that abstract HTML/CSS complexity.

Capabilities

Base Widget System

Foundation classes for all UI components with common functionality.

class Widget:
    """
    Base class for all UI widgets.
    """
    
    def __init__(self, parent: 'Widget' = None):
        """
        Initialize widget.
        
        Args:
            parent: Parent widget for hierarchical layout
        """
    
    def bind(self, event: str, callback: Callable) -> 'Widget':
        """
        Bind event handler to widget.
        
        Args:
            event: Event type ('click', 'change', etc.)
            callback: Event handler function
            
        Returns:
            Self for method chaining
        """
    
    def pack(self, **options) -> None:
        """
        Pack widget using layout manager.
        
        Args:
            **options: Layout options (side, fill, expand, etc.)
        """
    
    def place(self, x: int = 0, y: int = 0, width: int = None, height: int = None) -> None:
        """
        Place widget at absolute position.
        
        Args:
            x: X coordinate
            y: Y coordinate  
            width: Widget width
            height: Widget height
        """
    
    def grid(self, row: int = 0, column: int = 0, **options) -> None:
        """
        Place widget in grid layout.
        
        Args:
            row: Grid row
            column: Grid column
            **options: Grid options (rowspan, columnspan, sticky, etc.)
        """
    
    def show(self) -> None:
        """Show widget."""
    
    def hide(self) -> None:
        """Hide widget."""
    
    def destroy(self) -> None:
        """Remove widget from interface."""
    
    # Properties
    width: int         # Widget width
    height: int        # Widget height
    x: int            # X position
    y: int            # Y position
    visible: bool     # Visibility state
    enabled: bool     # Enabled state

Styling Classes

Comprehensive styling system for widget appearance and layout.

class Border:
    """Border styling configuration."""
    
    def __init__(self, width: int = 1, style: str = 'solid', color: str = 'black', radius: int = 0):
        """
        Configure border appearance.
        
        Args:
            width: Border width in pixels
            style: Border style ('solid', 'dashed', 'dotted', etc.)
            color: Border color
            radius: Border radius for rounded corners
        """

class Font:
    """Font styling configuration."""
    
    def __init__(self, family: str = 'Arial', size: int = 12, weight: str = 'normal', style: str = 'normal'):
        """
        Configure font appearance.
        
        Args:
            family: Font family name
            size: Font size in pixels
            weight: Font weight ('normal', 'bold', etc.)
            style: Font style ('normal', 'italic', etc.)
        """

class Padding:
    """Padding and margin configuration."""
    
    def __init__(self, top: int = 0, right: int = None, bottom: int = None, left: int = None):
        """
        Configure spacing around widget.
        
        Args:
            top: Top padding/margin
            right: Right padding/margin (defaults to top)
            bottom: Bottom padding/margin (defaults to top)  
            left: Left padding/margin (defaults to right)
        """

Container Widgets

Layout containers for organizing other widgets.

class Frame(Widget):
    """
    Container widget for grouping other widgets.
    """
    
    def __init__(self, parent: Widget = None, **options):
        """
        Create frame container.
        
        Args:
            parent: Parent widget
            **options: Frame options (border, background, etc.)
        """

class Box(Widget):
    """
    Flexible box layout container.
    """
    
    def __init__(self, parent: Widget = None, direction: str = 'vertical', **options):
        """
        Create box layout.
        
        Args:
            parent: Parent widget
            direction: Layout direction ('vertical', 'horizontal')
            **options: Box options (spacing, alignment, etc.)
        """

class Bar(Frame):
    """
    Toolbar/statusbar widget.
    """
    
    def __init__(self, parent: Widget = None, orientation: str = 'horizontal'):
        """
        Create toolbar.
        
        Args:
            parent: Parent widget
            orientation: Bar orientation ('horizontal', 'vertical')
        """

Usage:

from browser.ui import Frame, Box, Border, Font

# Create main container
main_frame = Frame(
    border=Border(width=2, style='solid', color='gray'),
    background='lightgray'
)

# Create vertical layout
content_box = Box(main_frame, direction='vertical', spacing=10)

# Create horizontal toolbar
toolbar = Bar(main_frame, orientation='horizontal')

Input Widgets

Interactive widgets for user input and data entry.

class Button(Widget):
    """
    Clickable button widget.
    """
    
    def __init__(self, text: str = "", parent: Widget = None, **options):
        """
        Create button.
        
        Args:
            text: Button text
            parent: Parent widget
            **options: Button options (font, color, etc.)
        """
    
    def click(self) -> None:
        """Programmatically click button."""
    
    # Properties
    text: str          # Button text
    enabled: bool      # Enabled state

class Entry(Widget):
    """
    Single-line text input widget.
    """
    
    def __init__(self, value: str = "", parent: Widget = None, **options):
        """
        Create text entry.
        
        Args:
            value: Initial text value
            parent: Parent widget
            **options: Entry options (placeholder, maxlength, etc.)
        """
    
    def get(self) -> str:
        """Get current text value."""
    
    def set(self, value: str) -> None:
        """Set text value."""
    
    def clear(self) -> None:
        """Clear text content."""
    
    def select_all(self) -> None:
        """Select all text."""
    
    # Properties
    value: str         # Current text value
    placeholder: str   # Placeholder text
    readonly: bool     # Read-only state

class Text(Widget):
    """
    Multi-line text widget.
    """
    
    def __init__(self, content: str = "", parent: Widget = None, **options):
        """
        Create text area.
        
        Args:
            content: Initial text content
            parent: Parent widget
            **options: Text options (rows, cols, wrap, etc.)
        """
    
    def insert(self, position: str, text: str) -> None:
        """Insert text at position."""
    
    def delete(self, start: str, end: str = None) -> None:
        """Delete text range."""
    
    def get(self, start: str = None, end: str = None) -> str:
        """Get text content or range."""
    
    # Properties
    content: str       # Text content
    wrap: str         # Text wrapping ('none', 'word', 'char')

Usage:

from browser.ui import Button, Entry, Text, Font

def create_form():
    # Create form elements
    name_entry = Entry(placeholder="Enter your name")
    email_entry = Entry(placeholder="Enter email address")
    
    message_text = Text(
        content="Type your message here...",
        rows=5,
        cols=40,
        wrap='word'
    )
    
    submit_btn = Button(
        text="Submit Form",
        font=Font(size=14, weight='bold')
    )
    
    # Handle form submission
    def handle_submit(event):
        name = name_entry.get()
        email = email_entry.get()
        message = message_text.get()
        
        if name and email and message:
            print(f"Form submitted: {name}, {email}")
            # Process form data
        else:
            print("Please fill all fields")
    
    submit_btn.bind('click', handle_submit)
    
    return [name_entry, email_entry, message_text, submit_btn]

Display Widgets

Widgets for displaying information and media content.

class Label(Widget):
    """
    Text display widget.
    """
    
    def __init__(self, text: str = "", parent: Widget = None, **options):
        """
        Create text label.
        
        Args:
            text: Display text
            parent: Parent widget
            **options: Label options (font, color, alignment, etc.)
        """
    
    # Properties
    text: str          # Display text
    alignment: str     # Text alignment ('left', 'center', 'right')

class Image(Widget):
    """
    Image display widget.
    """
    
    def __init__(self, src: str = "", parent: Widget = None, **options):
        """
        Create image widget.
        
        Args:
            src: Image source URL
            parent: Parent widget
            **options: Image options (alt, width, height, etc.)
        """
    
    def load_image(self, src: str) -> None:
        """Load new image."""
    
    # Properties
    src: str          # Image source
    alt: str          # Alternative text

Selection Widgets

Widgets for choosing from multiple options.

class Listbox(Frame):
    """
    List selection widget.
    """
    
    def __init__(self, parent: Widget = None, **options):
        """
        Create listbox.
        
        Args:
            parent: Parent widget
            **options: Listbox options (multiple, height, etc.)
        """
    
    def insert(self, index: int, item: str) -> None:
        """Insert item at index."""
    
    def delete(self, index: int) -> None:
        """Delete item at index."""
    
    def select(self, index: int) -> None:
        """Select item by index."""
    
    def get_selection(self) -> list[int]:
        """Get selected item indices."""
    
    def get_items(self) -> list[str]:
        """Get all items."""
    
    # Properties
    selection: list[int]  # Selected indices
    multiple: bool        # Allow multiple selection

class Checkbuttons(Frame):
    """
    Checkbox group widget.
    """
    
    def __init__(self, options: list[str], parent: Widget = None, **kwargs):
        """
        Create checkbox group.
        
        Args:
            options: List of checkbox labels
            parent: Parent widget
            **kwargs: Group options
        """
    
    def get_checked(self) -> list[str]:
        """Get checked option labels."""
    
    def set_checked(self, labels: list[str]) -> None:
        """Set checked options."""

class Radiobuttons(Frame):
    """
    Radio button group widget.
    """
    
    def __init__(self, options: list[str], parent: Widget = None, **kwargs):
        """
        Create radio button group.
        
        Args:
            options: List of radio button labels
            parent: Parent widget
            **kwargs: Group options
        """
    
    def get_selected(self) -> str:
        """Get selected option label."""
    
    def set_selected(self, label: str) -> None:
        """Set selected option."""

Usage:

from browser.ui import Listbox, Checkbuttons, Radiobuttons

def create_selection_widgets():
    # Create listbox with items
    item_list = Listbox(multiple=True)
    item_list.insert(0, "Item 1")
    item_list.insert(1, "Item 2") 
    item_list.insert(2, "Item 3")
    
    # Create checkbox group
    features = Checkbuttons([
        "Enable notifications",
        "Auto-save documents", 
        "Dark theme",
        "Advanced features"
    ])
    
    # Create radio button group
    priority = Radiobuttons([
        "Low priority",
        "Medium priority",
        "High priority",
        "Critical"
    ])
    
    def get_selections():
        selected_items = [item_list.get_items()[i] for i in item_list.get_selection()]
        checked_features = features.get_checked()
        selected_priority = priority.get_selected()
        
        print("Selected items:", selected_items)
        print("Checked features:", checked_features)
        print("Priority:", selected_priority)
    
    return item_list, features, priority

Dialog Widgets

Modal dialogs and popup windows for user interaction.

class Dialog(Widget):
    """
    Modal dialog widget.
    """
    
    def __init__(self, title: str = "", parent: Widget = None, **options):
        """
        Create modal dialog.
        
        Args:
            title: Dialog title
            parent: Parent widget
            **options: Dialog options (modal, resizable, etc.)
        """
    
    def show_modal(self) -> None:
        """Show dialog as modal."""
    
    def close(self) -> None:
        """Close dialog."""
    
    def add_button(self, text: str, callback: Callable) -> Button:
        """Add button to dialog."""
    
    # Properties
    title: str         # Dialog title
    modal: bool        # Modal state

class EntryDialog(Dialog):
    """
    Dialog with text entry field.
    """
    
    def __init__(self, title: str = "", prompt: str = "", parent: Widget = None):
        """
        Create entry dialog.
        
        Args:
            title: Dialog title
            prompt: Entry prompt text
            parent: Parent widget
        """
    
    def get_value(self) -> str:
        """Get entered value."""

class InfoDialog(Dialog):
    """
    Information display dialog.
    """
    
    def __init__(self, title: str = "", message: str = "", parent: Widget = None):
        """
        Create info dialog.
        
        Args:
            title: Dialog title
            message: Information message
            parent: Parent widget
        """

# Convenience functions
def Info(message: str, title: str = "Information") -> None:
    """Show information dialog."""

def Confirm(message: str, title: str = "Confirm") -> bool:
    """Show confirmation dialog."""

def Prompt(message: str, title: str = "Input", default: str = "") -> str:
    """Show input prompt dialog."""

Usage:

from browser.ui import Dialog, EntryDialog, InfoDialog, Info, Confirm, Prompt

def show_dialogs():
    # Simple info dialog
    Info("Operation completed successfully!")
    
    # Confirmation dialog
    if Confirm("Are you sure you want to delete this item?"):
        print("Item deleted")
    
    # Input prompt
    name = Prompt("Please enter your name:", default="Anonymous")
    if name:
        print(f"Hello, {name}!")
    
    # Custom dialog
    settings_dialog = Dialog("Settings", modal=True)
    
    # Add content to dialog
    content_frame = Frame(settings_dialog)
    
    theme_label = Label("Theme:", content_frame)
    theme_radio = Radiobuttons(["Light", "Dark"], content_frame)
    
    def save_settings():
        selected_theme = theme_radio.get_selected()
        print(f"Theme set to: {selected_theme}")
        settings_dialog.close()
    
    def cancel_settings():
        settings_dialog.close()
    
    settings_dialog.add_button("Save", save_settings)
    settings_dialog.add_button("Cancel", cancel_settings)
    
    settings_dialog.show_modal()

Layout Management

Advanced layout systems for complex interfaces.

class GridLayout:
    """
    Grid-based layout manager.
    """
    
    def __init__(self, rows: int, columns: int):
        """
        Create grid layout.
        
        Args:
            rows: Number of rows
            columns: Number of columns
        """
    
    def add_widget(self, widget: Widget, row: int, column: int, 
                   rowspan: int = 1, columnspan: int = 1) -> None:
        """Add widget to grid position."""

class BoxLayout:
    """
    Linear box layout manager.
    """
    
    def __init__(self, direction: str = 'vertical'):
        """
        Create box layout.
        
        Args:
            direction: Layout direction ('vertical', 'horizontal')
        """
    
    def add_widget(self, widget: Widget, flex: int = 0) -> None:
        """Add widget with flex weight."""

Complete Application Example

from browser.ui import *

class TodoApp:
    def __init__(self):
        self.setup_ui()
        self.todos = []
    
    def setup_ui(self):
        # Main window
        self.window = Frame(
            border=Border(width=1, color='gray'),
            background='white'
        )
        
        # Title
        title = Label(
            "Todo Application",
            font=Font(size=18, weight='bold'),
            alignment='center'
        )
        
        # Input section
        input_frame = Frame(self.window)
        self.todo_entry = Entry(placeholder="Enter new todo...")
        add_button = Button("Add Todo")
        add_button.bind('click', self.add_todo)
        
        # Todo list
        self.todo_list = Listbox(self.window, height=300)
        
        # Action buttons
        button_frame = Frame(self.window)
        complete_btn = Button("Mark Complete")
        delete_btn = Button("Delete")
        clear_btn = Button("Clear All")
        
        complete_btn.bind('click', self.mark_complete)
        delete_btn.bind('click', self.delete_todo)
        clear_btn.bind('click', self.clear_all)
        
        # Layout
        title.pack(fill='x', pady=10)
        
        input_frame.pack(fill='x', padx=10, pady=5)
        self.todo_entry.pack(side='left', fill='x', expand=True)
        add_button.pack(side='right', padx=(10, 0))
        
        self.todo_list.pack(fill='both', expand=True, padx=10, pady=5)
        
        button_frame.pack(fill='x', padx=10, pady=5)
        complete_btn.pack(side='left')
        delete_btn.pack(side='left', padx=(10, 0))
        clear_btn.pack(side='right')
    
    def add_todo(self, event):
        text = self.todo_entry.get().strip()
        if text:
            self.todos.append({"text": text, "completed": False})
            self.update_list()
            self.todo_entry.clear()
    
    def update_list(self):
        self.todo_list.clear()
        for i, todo in enumerate(self.todos):
            status = "✓ " if todo["completed"] else "○ "
            self.todo_list.insert(i, status + todo["text"])
    
    def mark_complete(self, event):
        selection = self.todo_list.get_selection()
        if selection:
            index = selection[0]
            self.todos[index]["completed"] = True
            self.update_list()
    
    def delete_todo(self, event):
        selection = self.todo_list.get_selection()
        if selection and Confirm("Delete selected todo?"):
            index = selection[0]
            del self.todos[index]
            self.update_list()
    
    def clear_all(self, event):
        if self.todos and Confirm("Clear all todos?"):
            self.todos.clear()
            self.update_list()

# Run application
app = TodoApp()
app.window.show()

This comprehensive UI framework enables creation of sophisticated desktop-style applications in web browsers using familiar widget concepts and Python syntax, while automatically handling HTML/CSS generation and browser compatibility.

Install with Tessl CLI

npx tessl i tessl/pypi-brython

docs

ajax-networking.md

browser-integration.md

cli-tools.md

html-elements.md

index.md

runtime-engine.md

storage.md

timers-animation.md

ui-framework.md

websocket.md

tile.json