### Minimal pysciter Application Setup
Source: https://github.com/sciter-sdk/pysciter/blob/master/README.md
This Python code demonstrates the basic structure of a pysciter application. It initializes a Sciter window, loads an HTML file, expands the window to fill the screen, and starts the application's event loop. This serves as a starting point for creating GUI applications with pysciter.
```python
import sciter
if __name__ == '__main__':
frame = sciter.Window(ismain=True, uni_theme=True)
frame.load_file("minimal.htm")
frame.expand()
frame.run_app()
```
--------------------------------
### Python Sciter Window Loading and Resource Management
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
Illustrates Sciter window loading and custom resource handling in Python. It includes methods for intercepting and responding to resource requests, custom data loading, and handling debug output. This example configures Sciter options, sets a home URL, and demonstrates loading HTML files.
```python
import sciter
class AppWindow(sciter.Window):
def __init__(self):
super().__init__(ismain=True, uni_theme=True)
self.setup_debug(debug_windows=True, debug_output=True)
def on_load_data(self, nm):
"""Handle resource loading"""
from sciter.capi.screquest import SciterResourceType
uri = nm.uri
print(f"Loading: {uri}")
# Custom resource handling
if uri.startswith("app://custom/"):
custom_data = b"
Custom content"
self.data_ready(uri, custom_data, request_id=nm.requestId)
return 1 # Handled
return 0 # Let Sciter handle it
def on_data_loaded(self, nm):
"""Called when resource loaded"""
uri = nm.uri
status = nm.status
print(f"Loaded: {uri} (status: {status})")
return 0
def on_debug_output(self, tag, subsystem, severity, text, text_len):
"""Custom debug output handler"""
import sys
from sciter.capi.scdef import OUTPUT_SEVERITY
if severity == OUTPUT_SEVERITY.ERROR:
print(f"ERROR: {text}", file=sys.stderr)
else:
print(f"DEBUG: {text}", file=sys.stdout)
# Configure Sciter options
sciter.set_option(
sciter.capi.scdef.SCITER_RT_OPTIONS.SCITER_SET_DEBUG_MODE,
True
)
frame = AppWindow()
# Set home URL for relative paths
frame.set_home_url("file:///app/")
# Load with different methods
frame.load_file("examples/app.html")
# frame.load_html(b"...", uri="app://main.html")
frame.run_app()
```
--------------------------------
### Style Sciter Elements and Manage State
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
Covers setting and getting style attributes (like color, font-size) directly on elements. It also demonstrates managing element states (e.g., disabled) using set_state and has_state, and retrieving element dimensions and highlighting.
```python
import sciter
from sciter.capi.scdom import ELEMENT_STATE_BITS
frame = sciter.Window(ismain=True, uni_theme=True)
frame.load_html(b"""
""")
root = frame.get_root()
button = root.find_first('#myBtn')
# Set style attributes
button.set_style_attribute('color', 'red')
button.set_style_attribute('font-size', '20px')
button.set_style_attribute('background-color', '#f0f0f0')
# Get style attributes
color = button.style_attribute('color')
print(f"Color: {color}")
# Manage element state
button.set_state(ELEMENT_STATE_BITS.STATE_DISABLED, update=True)
current_state = button.state()
has_disabled = button.has_state(ELEMENT_STATE_BITS.STATE_DISABLED)
print(f"Is disabled: {has_disabled}")
# Clear disabled state
button.set_state(0, clear_bits=ELEMENT_STATE_BITS.STATE_DISABLED, update=True)
# Get element location
location = button.get_location()
print(f"Position: ({location.left}, {location.top})")
print(f"Size: {location.right - location.left}x{location.bottom - location.top}")
# Highlight element for debugging
button.highlight(isset=True)
frame.run_app()
```
--------------------------------
### Sciter DOM Element Creation and Modification in Python
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
Provides a Python example for creating new DOM elements and appending them to existing elements within a Sciter window. Demonstrates finding a target element and then using methods to dynamically add new HTML content.
```python
import sciter
frame = sciter.Window(ismain=True, uni_theme=True)
frame.load_html(b'')
root = frame.get_root()
app_div = root.find_first('#app')
# Example of creating and appending a new element (implementation details omitted for brevity)
# new_element = frame.create_element('div', {'id': 'new_item'})
# new_element.set_text('This is a new element')
# app_div.append_child(new_element)
# frame.run_app()
```
--------------------------------
### Sciter JavaScript API with Modules
Source: https://github.com/sciter-sdk/pysciter/blob/master/examples/pysciter.htm
This JavaScript code snippet shows how to import and use modules like '@env' and '@sciter' within a Sciter application. It demonstrates setting the window caption, updating UI elements with environment-specific information, and calling Sciter's internal functions like version and revision. It also includes examples of calling native functions using `xcall` and handling asynchronous operations.
```javascript
import * as env from "@env";
import * as sciter from "@sciter";
Window.this.caption = document.$("head > title").value;
document.$("#kind").innerText = ".JS";
document.$("#machine").innerText = env.machineName();
document.$("#version").innerText = sciter.VERSION;
document.$("#revision").innerText = sciter.REVISION;
document.on("click", "button#ti2py", function() {
var answer = Window.this.xcall("PythonCall", Window.this.caption);
document.$("body").append(
script -> python: {answer}
);
});
async function async_call(name, ...args) {
return new Promise((resolve, reject) => {
return Window.this.xcall(name, args, resolve, reject);
});
}
document.on("click", "#async", async function() {
console.log("calling AsyncTask");
try {
let r = await async_call("AsyncTask", 1, 2);
console.log("async result", r);
} catch (e) {
console.log("async exception", e);
}
});
document.on("click", "#thread", function() {
console.log("calling AsyncThread");
try {
let r = Window.this.xcall("AsyncThread", 1, 2);
console.log("thread result", r);
} catch (e) {
console.log("thread exception", e);
}
});
```
--------------------------------
### Traverse Sciter Element Tree
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
Illustrates how to navigate the Sciter element hierarchy using methods like parent(), next_sibling(), prev_sibling(), and accessing children by index or iteration. It also shows how to find elements by CSS selectors and get the root element.
```python
import sciter
frame = sciter.Window(ismain=True, uni_theme=True)
frame.load_html(b"""
FirstMiddleLast
""")
root = frame.get_root()
middle = root.find_first('#middle')
# Navigate element tree
parent = middle.parent()
print(f"Parent ID: {parent.attribute('id')}") # Output: parent
next_el = middle.next_sibling()
print(f"Next sibling text: {next_el.get_text()}") # Output: Last
prev_el = middle.prev_sibling()
print(f"Previous sibling text: {prev_el.get_text()}") # Output: First
# Access children
parent_div = root.find_first('#parent')
child_count = parent_div.children_count()
print(f"Children count: {child_count}") # Output: Children: 3
first_child = parent_div[0] # Index access
last_child = parent_div[-1]
# Iterate children
print("Iterating children:")
for i in range(len(parent_div)):
child = parent_div[i]
print(f" Child {i}: {child.get_text()}")
# Get root element
root_element = middle.root()
print(f"Root tag: {root_element.get_tag()}") # Output: html
frame.run_app()
```
--------------------------------
### PySciter Todo Application Example (Python)
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
A complete Python script that defines a Todo application using PySciter. It includes methods for adding, toggling, deleting, and saving todos, all exposed to the JavaScript frontend. The application leverages Python's `sciter` library and standard libraries like `json` and `time`.
```python
import sciter
import json
class TodoApp(sciter.Window):
def __init__(self):
super().__init__(ismain=True, uni_theme=True)
self.todos = []
self.set_dispatch_options(require_attribute=True)
@sciter.script
def get_todos(self):
"""Return all todos"""
return self.todos
@sciter.script
def add_todo(self, text):
"""Add new todo item"""
todo = {
'id': len(self.todos) + 1,
'text': text,
'completed': False
}
self.todos.append(todo)
return todo
@sciter.script
def toggle_todo(self, todo_id):
"""Toggle todo completion status"""
for todo in self.todos:
if todo['id'] == todo_id:
todo['completed'] = not todo['completed']
return True
return False
@sciter.script
def delete_todo(self, todo_id):
"""Delete todo by ID"""
self.todos = [t for t in self.todos if t['id'] != todo_id]
return True
@sciter.script(convert=True, promise=True)
def save_todos(self):
"""Async save operation"""
import time
time.sleep(1) # Simulate I/O
with open('todos.json', 'w') as f:
json.dump(self.todos, f)
return len(self.todos)
if __name__ == '__main__':
sciter.runtime_features(file_io=True, allow_sysinfo=True)
app = TodoApp()
app.load_html(b"""
Todo App
")
app.run_app()
```
--------------------------------
### Exposing Python Functions to Sciter
Source: https://github.com/sciter-sdk/pysciter/blob/master/README.md
This Python code defines a function `GetNativeApi` that returns a dictionary of native Python functions. These functions can then be called from within Sciter's TIScript or JavaScript. This example demonstrates exposing functions for addition, subtraction (including exception handling), and multiplication, showcasing interoperability.
```python
def GetNativeApi(): # called from sciter.EventHandler.on_script_call
def on_add(a, b):
return a + b
def on_sub(a, b):
raise Exception("sub(%d,%d) raised exception" % (a, b))
api = { 'add': on_add, # plain function
'sub': on_sub, # raise exception at script
'mul': lambda a,b: a * b } # lambdas supported too
return api
```
--------------------------------
### Calling Python from JavaScript
Source: https://github.com/sciter-sdk/pysciter/blob/master/README.md
This JavaScript code illustrates how to invoke Python functions that have been made available through the `GetNativeApi` method. It accesses the API object associated with the current window and calls the `add` function, logging the result to the console. This provides a clear example of cross-language function calls in pysciter.
```javascript
// `Window.this` represents the window where this script is running.
const api = Window.this.GetNativeApi();
console.log("2 + 3", api.add(2, 3));
```
--------------------------------
### Create Basic PySciter Window and Load Content
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
Demonstrates how to initialize a basic Sciter window in Python, enable runtime features, and load HTML content either from a file or directly from a byte string. This is the entry point for most PySciter applications.
```python
import sciter
# Enable runtime features (disabled by default since 4.2.5.0)
sciter.runtime_features(file_io=True, allow_sysinfo=True)
# Create main application window
frame = sciter.Window(ismain=True, uni_theme=True)
# Load HTML content from file
frame.load_file("examples/minimal.htm")
# Or load HTML from memory
html_content = b"
Hello World
"
frame.load_html(html_content, uri="app://main.html")
# Show window and run message loop
frame.expand() # Show or maximize window
frame.run_app() # Blocks until window closes
```
--------------------------------
### Tiscript: Print 'hello world' on Button Click
Source: https://github.com/sciter-sdk/pysciter/blob/master/examples/handlers.htm
This snippet shows a Tiscript button element that, when clicked, invokes the 'gprintln' function with a string and multiple arguments. It demonstrates basic event handling and outputting data within the Sciter environment.
```Tiscript
button#csss { click!:gprintln("hello world", 11,22,33,44); }
```
--------------------------------
### Sciter DOM Manipulation and Event Handling (Modules)
Source: https://github.com/sciter-sdk/pysciter/blob/master/examples/minimal.htm
This snippet demonstrates manipulating the Sciter DOM and handling user events using Sciter's module system (`@env`, `@sciter`). It sets the window caption, updates display elements with system information, appends list items dynamically, and handles file selection. Dependencies include the 'env' and 'sciter' modules, and the `Window` object.
```html
Minimal Sciter Demo
Inspector tool from the Sciter SDK.
```
--------------------------------
### Configure and Control PySciter Window Properties
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
Shows how to create a Sciter window with various configuration options such as resizability, theming, debugging, and initial position/size. It also covers common window operations like setting the title, maximizing, minimizing, and closing the window.
```python
import sciter
from sciter.capi.scdef import SCITER_CREATE_WINDOW_FLAGS
# Create window with custom settings
frame = sciter.Window(
ismain=True, # Main application window
resizeable=True, # Allow window resizing
uni_theme=True, # Use unified OS theme
debug=True, # Enable debug inspector
pos=(100, 100), # Window position (x, y)
size=(800, 600) # Window size (width, height)
)
# Window operations
frame.set_title("My Application")
title = frame.get_title()
frame.expand(maximize=True) # Maximize window
frame.collapse(hide=False) # Minimize window
frame.dismiss() # Close window
frame.quit_app(code=0) # Post quit message
# Load content and run
frame.load_file("file:///path/to/app.html")
frame.run_app()
```
--------------------------------
### Sciter DOM Manipulation and Event Handling (Sciter Native)
Source: https://github.com/sciter-sdk/pysciter/blob/master/examples/minimal.htm
This snippet demonstrates manipulating the Sciter DOM and handling user events using Sciter's native JavaScript API. It sets the window caption, updates display elements with system information, appends list items dynamically, and handles file selection. Dependencies include Sciter's built-in objects like `Sciter`, `view`, and `stdout`.
```html
Minimal Sciter Demo
Inspector tool from the Sciter SDK.
```
--------------------------------
### Create and Append Sciter Elements
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
Demonstrates how to create new HTML elements (headings, paragraphs, buttons, lists) using sciter.Element.create and append them to the DOM. It also shows how to clone existing elements and detach them from the DOM.
```python
import sciter
# Assume app_div and frame are already initialized sciter elements/windows
# Example initialization (not part of the core snippet):
# app_div = sciter.Element.create('div')
# frame = sciter.Window(ismain=True)
# frame.attach_dom(app_div)
# Create new element
new_heading = sciter.Element.create('h1', 'Dynamic Title')
new_paragraph = sciter.Element.create('p', 'This is a dynamically created paragraph.')
# Append elements to DOM
# app_div.append(new_heading)
# app_div.append(new_paragraph)
# Create and configure element
button = sciter.Element.create('button')
button.set_text('Click Me')
button.set_attribute('id', 'dynamicBtn')
button.set_attribute('class', 'primary-button')
# app_div.append(button)
# Create complex structure
list_element = sciter.Element.create('ul')
for i in range(5):
item = sciter.Element.create('li', f'Item {i+1}')
list_element.append(item)
# app_div.append(list_element)
# Clone existing element
cloned_button = button.clone()
cloned_button.set_attribute('id', 'clonedBtn')
# app_div.append(cloned_button)
# Remove element
button.detach() # Remove from DOM but keep in memory
# button.destroy() # Remove and destroy completely
# frame.run_app() # This would typically run the Sciter application
```
--------------------------------
### Sciter HTML Structure and Styling
Source: https://github.com/sciter-sdk/pysciter/blob/master/examples/pysciter.htm
This snippet defines the basic HTML structure and styling for a Sciter application. It includes CSS for background gradients, text color, and RTL (right-to-left) text mapping. It also demonstrates how to set the window caption and update elements with dynamic information like machine name and Sciter version.
```html
PySciter Sample
```
--------------------------------
### Tiscript: Define and Call a Script Method
Source: https://github.com/sciter-sdk/pysciter/blob/master/examples/handlers.htm
This Tiscript code assigns a function as a method 'mfn' to the root element, demonstrating object-oriented programming within the script. It shows how to define and invoke methods associated with Sciter elements.
```Tiscript
var root = view.root;
root.mfn = function(a, b){
return String.printf("script defined method function with arg, a:%v, b:%v", a, b);
};
```
--------------------------------
### Python Sciter Event Handling and Behaviors
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
Demonstrates how to create a custom event handler in Python for Sciter, including methods for attached elements, document completion, general event handling (like button clicks), script calls, and callable Python methods from JavaScript. It sets up a Sciter window with a custom handler and loads HTML content.
```python
import sciter
from sciter.event import EventHandler, BEHAVIOR_EVENTS
class MyHandler(EventHandler):
def __init__(self):
super().__init__()
def attached(self, he):
"""Called when handler attached to element"""
print("Handler attached to:", sciter.Element(he))
def document_complete(self):
"""Called when document fully loaded"""
print("Document loaded")
if self.element:
print("Root element:", self.element.get_tag())
def on_event(self, source, target, code, phase, reason):
"""Handle behavior events"""
from sciter.capi.scbehavior import PHASE_MASK
if code == BEHAVIOR_EVENTS.BUTTON_CLICK:
target_el = sciter.Element(target)
print(f"Button clicked: {target_el.attribute('id')}")
return True # Event handled
return False # Event not handled
def on_script_call(self, name, args):
"""Handle script function calls"""
print(f"Script called: {name} with args: {args}")
if name == "handleClick":
print("Custom click handler")
return "Handled by Python"
return None # Not handled
@sciter.script
def python_method(self, data):
"""Method callable from JavaScript"""
print(f"Python method called with: {data}")
return {"status": "success", "data": data}
# Create window with custom handler
frame = sciter.Window(ismain=True, uni_theme=True)
handler = MyHandler()
frame.attach(window=frame.hwnd)
frame.load_html(b"""
""")
frame.run_app()
```
--------------------------------
### Sciter JavaScript Event Handling and DOM Manipulation
Source: https://github.com/sciter-sdk/pysciter/blob/master/examples/pysciter.htm
This JavaScript code demonstrates event handling and DOM manipulation within Sciter. It includes functionality for appending new elements, opening file dialogs, calling Python functions from script, and executing asynchronous operations using promises. It also shows how to access Sciter's version information and interact with native APIs.
```javascript
view.caption = $(head > title).value;
$(#kind).text = ".TIS";
$(#machine).text = Sciter.machineName();
$(#version).text = String.printf("%d.%d.%d.%d", (Sciter.VERSION >> 16) & 0xffff, Sciter.VERSION & 0xffff, (Sciter.REVISION >> 16) & 0xffff, Sciter.REVISION & 0xffff);
try {
// since 4.2.5.0
$(#revision).text = Sciter.BUILD.toString();
} catch(e) {
$(#revision).text = "N/A";
}
var counter = 0;
$(button#append).on("click", function() {
$(body).$append(
);
return "its working!";
}
function raise_error(arg) {
throw new Error(String.$(Unexpected type of input {typeof arg}.));
}
self.timer(2000, function() {
if(!view.api) view.api = view.GetNativeApi();
// {add: function(a,b) { return a + b; }};
stdout.println(String.printf("2 + 3 = %d", view.api.add(2, 3)));
stdout.println(String.printf("2 * 3 = %d", view.api.mul(2, 3)));
stdout.println(String.printf("2 - 3 = %d", view.api.sub(2, 3)));
});
```
--------------------------------
### Tiscript: Handle Click Event to Call Native 'sumall' Method
Source: https://github.com/sciter-sdk/pysciter/blob/master/examples/handlers.htm
This Tiscript code sets up a click event listener for the element with ID 'sumall'. When clicked, it calls the native Sciter function 'view.sumall' with several numerical arguments and prints the result using 'view.gprintln'.
```Tiscript
root.$(#sumall).on("click", function() {
view.gprintln("sumall(1,2,3,45):", view.sumall(1,2,3,45));
});
```
--------------------------------
### Call JavaScript Functions from Python
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
Illustrates how to invoke JavaScript functions defined within the loaded HTML from your Python code. This includes passing arguments to JavaScript functions and retrieving their return values. It also demonstrates evaluating arbitrary JavaScript expressions and obtaining function references.
```python
import sciter
frame = sciter.Window(ismain=True, uni_theme=True)
frame.load_html(b"""
Ready
""")
# Call JavaScript function with arguments
result = frame.call_function('greet', "Python")
print(result.get_value()) # Output: Hello, Python!
# Call function with multiple arguments
result = frame.call_function('calculate', 5, 3)
data = result.get_value()
print(data) # Output: {'sum': 8, 'product': 15}
# Evaluate JavaScript expressions
result = frame.eval_script('2 + 2')
print(result.get_value()) # Output: 4
# Get reference to function and call it later
func = frame.eval_script('greet')
result = func.call('World', name='greeting')
print(result) # Output: Hello, World!
frame.run_app()
```
--------------------------------
### Expose Python Methods to JavaScript
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
Demonstrates how to make Python methods callable from JavaScript using the `@sciter.script` decorator. This allows for seamless integration where JavaScript can trigger Python logic. It covers basic function calls, returning complex data types, receiving data from JavaScript, and aliasing method names.
```python
import sciter
class MyWindow(sciter.Window):
def __init__(self):
super().__init__(ismain=True, uni_theme=True)
# Method called from JavaScript
@sciter.script
def add_numbers(self, a, b):
"""Simple function exposed to JavaScript"""
return a + b
@sciter.script
def get_user_data(self):
"""Return complex data to JavaScript"""
return {
'name': 'John Doe',
'age': 30,
'scores': [95, 87, 92]
}
@sciter.script
def process_data(self, data):
"""Receive and process data from JavaScript"""
print(f"Received: {data}")
return {"status": "processed", "count": len(data)}
@sciter.script('customName')
def method_with_alias(self):
"""Exposed with different name in JavaScript"""
return "Called via alias"
if __name__ == '__main__':
sciter.runtime_features(file_io=True)
frame = MyWindow()
frame.load_html(b"""
Check console output
""")
frame.run_app()
```
--------------------------------
### Tiscript: Define and Call a Script Function
Source: https://github.com/sciter-sdk/pysciter/blob/master/examples/handlers.htm
This Tiscript code defines a global function 'gFunc' that accepts two arguments and returns a formatted string. It illustrates how to declare and utilize functions directly within the Sciter script.
```Tiscript
// for host calls
function gFunc(a,b){
return String.printf("script defined function with arg, a:%v, b:%v", a, b);
}
```
--------------------------------
### Calling Python from TIScript
Source: https://github.com/sciter-sdk/pysciter/blob/master/README.md
This TIScript code demonstrates how to call native Python functions exposed via `GetNativeApi` from within a Sciter TIScript environment. It retrieves the API object and then calls the `add` function, printing the result to the standard output stream. This highlights the seamless integration between the scripting and Python layers.
```javascript
// `view` represents window where script is runnung.
// `stdout` stream is a standard output stream (shell or debugger console, for example)
var api = view.GetNativeApi();
// returned `api` object looks like {add: function(a,b) { return a + b; }};
stdout.println("2 + 3 = " + api.add(2, 3));
```
--------------------------------
### Async Python Functions with Sciter
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
Illustrates how to run long-running Python tasks in separate threads without blocking the Sciter UI using `@sciter.script(threading=True)`. It also shows how to return promises to JavaScript for asynchronous operations with `@sciter.script(promise=True)`, allowing JavaScript to `await` the results.
```python
import sciter
import time
class AsyncWindow(sciter.Window):
def __init__(self):
super().__init__(ismain=True, uni_theme=True)
@sciter.script(convert=True, threading=True)
def long_running_task(self, duration):
"""Runs in separate thread, doesn't block UI"""
print(f"Starting task for {duration} seconds")
time.sleep(duration)
print("Task completed")
return f"Completed after {duration}s"
@sciter.script(convert=True, promise=True)
def async_operation(self, value):
"""Returns promise to JavaScript, runs in thread"""
print(f"Processing {value}")
time.sleep(2)
result = value * 2
print(f"Result: {result}")
return result
if __name__ == '__main__':
sciter.runtime_features(file_io=True)
frame = AsyncWindow()
frame.load_html(b"""
""")
frame.run_app()
```
--------------------------------
### Python-JS API Integration with Sciter
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
Demonstrates how to expose Python functions and data to JavaScript within a Sciter window. Uses the `@sciter.script` decorator to expose Python methods as API functions accessible from JavaScript. It shows calling functions, accessing data, and handling errors across the language boundary.
```python
import sciter
class AppWindow(sciter.Window):
def __init__(self):
super().__init__(ismain=True, uni_theme=True)
@sciter.script
def GetNativeApi(self):
"""Return object with multiple functions to JavaScript"""
def on_add(a, b):
return a + b
def on_multiply(a, b):
return a * b
def on_process(text):
return text.upper()
def on_error():
raise Exception("Intentional error from Python")
# Return dictionary of functions
api = {
'add': on_add,
'multiply': on_multiply,
'process': on_process,
'error': on_error,
'data': {'version': '1.0', 'ready': True}
}
return api
if __name__ == '__main__':
sciter.runtime_features(file_io=True)
frame = AppWindow()
frame.load_html(b"""
API Integration Example
""")
frame.run_app()
```
--------------------------------
### Python Sciter Element Events and Scripting
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
Demonstrates how to interact with HTML elements in Sciter using Python, including sending synthetic and posted events, firing custom events with data, executing JavaScript within an element's context, calling element methods, and invoking global functions. It loads an HTML document and manipulates its elements.
```python
import sciter
from sciter.capi.scbehavior import BEHAVIOR_EVENTS, CLICK_REASON
frame = sciter.Window(ismain=True, uni_theme=True)
frame.load_html(b"""
""")
root = frame.get_root()
button = root.find_first('#testBtn')
result_div = root.find_first('#result')
# Send synthetic event to element
handled = button.send_event(
BEHAVIOR_EVENTS.BUTTON_CLICK,
reason=CLICK_REASON.SYNTHESIZED
)
print(f"Event handled: {handled}")
# Post event (asynchronous)
button.post_event(BEHAVIOR_EVENTS.BUTTON_CLICK)
# Fire custom event with data
button.fire_event(
BEHAVIOR_EVENTS.BUTTON_CLICK,
data={'custom': 'data', 'value': 123},
post=False # Synchronous
)
# Execute script in element context
result = button.eval_script(
"""
this.style.backgroundColor = 'yellow';
return 'Button styled';
""", name='button_script')
print(result.get_value())
# Call element method
button.call_method('click')
# Call global function in element's namespace
result = result_div.call_function('Array.from', [1, 2, 3])
print(result.get_value())
frame.run_app()
```
--------------------------------
### Sciter DOM Element Access and Manipulation in Python
Source: https://context7.com/sciter-sdk/pysciter/llms.txt
Shows how to access and manipulate Document Object Model (DOM) elements within a Sciter window using Python. Covers finding elements by CSS selectors, getting/setting text and HTML content, managing attributes, and checking element visibility and enabled states.
```python
import sciter
frame = sciter.Window(ismain=True, uni_theme=True)
frame.load_html(b"""
Welcome
Hello World
""")
# Get root element
root = frame.get_root()
# Find elements by CSS selector
title = root.find_first('h1.title')
print(title.get_text()) # Output: Welcome
# Find all matching elements
all_elements = root.find_all('div#container > *')
for el in all_elements:
print(el.get_tag(), el.get_text())
# Get/set element content
button = root.find_first('#myButton')
button.set_text('New Button Text')
text = button.get_text()
# Get/set HTML content
html = button.get_html(outer=True)
print(html) # Output: b''
# Set inner HTML
container = root.find_first('#container')
container.set_html(b'
Updated Content
New paragraph
')
# Element attributes
button.set_attribute('disabled', 'true')
id_value = button.attribute('id')
button.remove_attribute('disabled')
# Element state and visibility
is_visible = button.is_visible()
is_enabled = button.is_enabled()
frame.run_app()
```
--------------------------------
### Tiscript: Handle Click Event for Native Method Call
Source: https://github.com/sciter-sdk/pysciter/blob/master/examples/handlers.htm
This Tiscript snippet attaches a click event handler to the element with the ID 'mcall'. On click, it invokes the native Sciter method 'root.mcall' with a string and a floating-point number as arguments.
```Tiscript
self.$(#mcall).on("click", function() {
root.mcall("nice to see you", 100.5, 123);
});
```
--------------------------------
### Tiscript: Handle Click Event to Call Native Function and Output
Source: https://github.com/sciter-sdk/pysciter/blob/master/examples/handlers.htm
This Tiscript snippet defines a click event handler for an element with the ID 'functor'. Upon clicking, it calls a native Sciter function 'view.kkk()', then uses 'view.gprintln' to display the result and the output of another method 'k.f()'.
```Tiscript
self.$(#functor).on("click", function() {
var k = view.kkk();
view.gprintln("gprintln kkkk" + String.printf(", k = %v", k));
view.gprintln("k.f(1,2,3,4.5):", k.f(1,2,3,4.5));
});
```
--------------------------------
### Calling Sciter Functions from Python
Source: https://github.com/sciter-sdk/pysciter/blob/master/README.md
This Python snippet shows how to invoke functions defined within the Sciter (TIScript or JavaScript) environment from your Python code. The `call_function` method allows passing arguments, including lists, to the script. This is useful for triggering UI updates or custom script logic from the backend.
```python
answer = self.call_function('script_function', "hello, python!", "and", ["other", 3, "arguments"])
```