library reference - itzmetanjim/py-positron GitHub Wiki

Library Reference

This document provides a comprehensive reference for the PyPositron library.

Core Functions

openUI(html_path, functions=None, width=900, height=700, title="Python UI", autostart=True)

Creates and displays a PyPositron application window. By default, automatically starts the application event loop and blocks until application is closed.

Parameters:

  • html_path (str): Path to the HTML file for the UI
  • functions (list, optional): List of Python functions to expose to the HTML
  • width (int, optional): Window width in pixels (default: 900)
  • height (int, optional): Window height in pixels (default: 700)
  • title (str, optional): Window title (default: "Python UI")
  • autostart (bool, optional): Whether to automatically start the event loop (default: True)

Returns:

  • Window: PyWebView window object

Example:

import py_positron as main

# Basic usage - automatically starts the application
main.openUI("views/index.html")

# With custom dimensions and title
main.openUI("views/index.html", None, 1200, 800, "My App")

# With exposed functions
def my_function():
    return "Hello from Python!"

main.openUI("views/index.html", [my_function])

# Manual control - disable autostart, this is optional
window = main.openUI("views/index.html", autostart=False)
# Do some setup...
main.start()  # Manually start when ready

start()

Starts the PyPositron application event loop. This function blocks until the application is closed.

Note: When using openUI() with autostart=True (default), calling start() is not necessary.

Example:

import py_positron as main

# Manual start (when autostart=False)
window = main.openUI("views/index.html", autostart=False)
main.start()  # Application runs until window is closed
print("Application closed")

Document Object

The document object provides methods to interact with the HTML DOM from Python code embedded in HTML.

document.getElementById(element_id)

Returns an Element object for the element with the specified ID.

Parameters:

  • element_id (str): The ID of the element

Returns:

  • Element: Element object

Example:

<py>
button = document.getElementById('my-button')
button.innerText = "Click me!"
</py>

document.getElementsByClassName(class_name)

Returns an ElementList of elements with the specified class name.

Parameters:

  • class_name (str): The class name to search for

Returns:

  • ElementList: Collection of elements

document.querySelector(selector)

Returns the first element that matches the CSS selector.

Parameters:

  • selector (str): CSS selector string

Returns:

  • Element: First matching element

document.querySelectorAll(selector)

Returns all elements that match the CSS selector.

Parameters:

  • selector (str): CSS selector string

Returns:

  • ElementList: Collection of matching elements

document.createElement(tag_name)

Creates a new HTML element.

Parameters:

  • tag_name (str): The tag name for the new element

Returns:

  • Element: New element object

document.alert(message)

Shows an alert dialog box.

Parameters:

  • message (str): Message to display

Example:

<py>
document.alert("Hello from Python!")
</py>

document.confirm(message)

Shows a confirmation dialog with Yes/No buttons.

Parameters:

  • message (str): Message to display

Returns:

  • bool: True if user clicked Yes, False if No

document.prompt(message, default_value=None)

Shows a prompt dialog for user input.

Parameters:

  • message (str): Prompt message
  • default_value (str, optional): Default input value

Returns:

  • str: User input or None if cancelled

Element Object

Element objects represent HTML elements and provide methods to interact with them.

Properties

element.innerText

Get or set the inner text content of the element.

<py>
heading = document.getElementById('title')
print(heading.innerText)  # Get text
heading.innerText = "New Title"  # Set text
</py>

element.innerHTML

Get or set the inner HTML content of the element.

Warning: Setting innerHTML can lead to XSS vulnerabilities if not sanitized properly.

<py>
div = document.getElementById('content')
div.innerHTML = "<p>New paragraph</p>"
</py>

element.value

Get or set the value of form elements (input, textarea, select).

<py>
input_field = document.getElementById('user-input')
print(input_field.value)  # Get value
input_field.value = "Default text"  # Set value
</py>

Methods

element.setAttribute(attr_name, value)

Sets an attribute on the element.

Parameters:

  • attr_name (str): Attribute name
  • value (str): Attribute value
<py>
button = document.getElementById('my-button')
button.setAttribute('disabled', 'true')
button.setAttribute('class', 'btn btn-primary')
</py>

element.addEventListener(event_type, callback)

Adds an event listener to the element.

Parameters:

  • event_type (str): Event type (e.g., 'click', 'change', 'input')
  • callback (function): Python function to call when event occurs
<py>
def handle_click():
    document.alert("Button was clicked!")

button = document.getElementById('my-button')
button.addEventListener('click', handle_click)
</py>

ElementList Object

ElementList represents a collection of elements (similar to NodeList in JavaScript).

Properties

elementlist.length

Returns the number of elements in the collection.

Methods

elementlist[index]

Access element by index.

<py>
divs = document.getElementsByClassName('content')
if len(divs) > 0:
    first_div = divs[0]
    first_div.innerText = "First div"
</py>

Iteration

ElementList supports iteration:

<py>
buttons = document.getElementsByClassName('btn')
for button in buttons:
    button.setAttribute('disabled', 'true')
</py>

Inline Python in HTML

PyPositron allows you to embed Python code directly in HTML using <py> tags.

Basic Usage

<py>
# Python code here
import time
current_time = time.strftime("%H:%M:%S")
print(f"Current time: {current_time}")
</py>

Available Objects

Within <py> tags, you have access to:

  • document: Document object for DOM manipulation
  • window: Window object for advanced operations
  • exposed: Access to exposed Python functions
  • Standard Python modules (can be imported)

Event Handling

<button id="time-btn">Show Time</button>

<py>
import time

def show_time():
    current_time = time.strftime("%H:%M:%S")
    document.alert(f"Current time: {current_time}")

button = document.getElementById('time-btn')
button.addEventListener('click', show_time)
</py>

Best Practices

  1. Keep it simple: Use <py> tags for initialization and event handlers
  2. Avoid complex logic: Move complex Python logic to separate modules
  3. Handle errors: Wrap code in try-catch blocks when needed
  4. Import at the top: Import modules at the beginning of <py> blocks
<py>
try:
    import requests
    # Code that might fail
except ImportError:
    document.alert("requests module not available")
except Exception as e:
    print(f"Error: {e}")
</py>

Error Handling

Common Errors

  1. Element not found: Always check if elements exist
  2. Import errors: Ensure required modules are installed
  3. JavaScript evaluation errors: Check console for JS errors

Debugging

<py>
# Debug: Check if element exists
element = document.getElementById('my-element')
if element:
    print("Element found")
else:
    print("Element not found")

# Debug: List event handlers
print("Event handlers:", window._py_context.event_handlers.keys())
</py>

Advanced Usage

Exposing Python Functions

You can expose Python functions to be called from JavaScript:

# main_app.py
import py_positron as main

def get_data():
    return {"message": "Hello from Python!"}

def process_data(data):
    return data.upper()

main.openUI("views/index.html", [get_data, process_data])
main.start()
<!-- views/index.html -->
<script>
// Call exposed functions from JavaScript
window.python.get_data().then(result => {
    console.log(result);
});

window.python.process_data("hello").then(result => {
    console.log(result); // "HELLO"
});
</script>

Threading Considerations

  • PyPositron runs in multiple threads
  • DOM operations should be done from the main thread
  • Use appropriate synchronization for shared data

Performance Tips

  1. Minimize DOM operations: Batch DOM updates when possible
  2. Use CSS for styling: Avoid setting styles via Python when CSS works
  3. Cache element references: Store frequently used elements in variables
  4. Optimize imports: Import modules once, not in every function
⚠️ **GitHub.com Fallback** ⚠️