### Run Hello World Example
Source: https://pywebview.flowrl.com/contributing/development.html
Execute the simple browser example to verify your setup. This should open a basic webview window.
```python
python examples/simple_browser.py
```
--------------------------------
### Create a Hello World window with pywebview
Source: https://pywebview.flowrl.com/2.4
Create a new window with a title and a URL to display. This is a basic example to get started.
```python
import webview
webview.create_window('Hello world', 'https://pywebview.flowrl.com/')
```
--------------------------------
### Set Up Virtual Environment and Install Dependencies
Source: https://pywebview.flowrl.com/contributing/development.html
Create a Python 3 virtual environment, activate it, and install pywebview with development dependencies. Also installs pytest for testing.
```bash
virtualenv -p python3 venv
source venv/bin/activate
pip install -e ".[dev]"
pip install pytest
```
--------------------------------
### Create Qt Webview Window
Source: https://pywebview.flowrl.com/examples/qt_test.html
Creates a non-resizable pywebview window with specified dimensions and starts it using the Qt GUI backend. Ensure pywebview is installed.
```python
import webview
if __name__ == '__main__':
# Create a non-resizable webview window with 800x600 dimensions
webview.create_window('Qt Example', 'http://flowrl.com')
webview.start(gui='qt')
```
--------------------------------
### Create Multiple Windows
Source: https://pywebview.flowrl.com/examples/multiple_windows.html
This snippet shows how to create two initial windows and then dynamically create a third window after the application loop has started. Ensure the webview library is installed.
```Python
import webview
def third_window():
# Create a new window after the loop started
webview.create_window('Window #3', html='
')
webview.start(third_window)
```
--------------------------------
### Install pywebview
Source: https://pywebview.flowrl.com/3.7
Install the pywebview library using pip. Additional libraries may be required on Linux.
```bash
pip install pywebview
```
--------------------------------
### Create and Start a Basic Window
Source: https://pywebview.flowrl.com/guide/usage.html
This is the minimum code required to create a window and start the pywebview GUI loop.
```python
import webview
window = webview.create_window('Woah dude!', 'https://pywebview.flowrl.com')
webview.start()
```
--------------------------------
### Install pywebview
Source: https://pywebview.flowrl.com/blog/pywebview5.html
Install pywebview using pip. This command should be run in your terminal or command prompt.
```bash
pip install pywebview
```
--------------------------------
### Install pywebview with QT support on Linux
Source: https://pywebview.flowrl.com/guide/installation.html
On Linux, explicitly install pywebview with QT support. This command installs PyQT6.
```bash
pip install pywebview[qt]
```
--------------------------------
### Minimize, Restore, and Maximize Window
Source: https://pywebview.flowrl.com/examples/window_state.html
This Python snippet demonstrates how to control the window state. It starts the window minimized, then restores, maximizes, and minimizes it again after specific delays. Ensure the 'webview' library is installed.
```python
from time import sleep
import webview
def minimize(window):
print('Window is started minimized')
sleep(5)
print('Restoring window')
window.restore()
sleep(5)
print('Maximizing window')
window.maximize()
sleep(5)
print('Minimizing window')
window.minimize()
if __name__ == '__main__':
window = webview.create_window(
'Minimize window example', html='
Minimize window
', minimized=True
)
webview.start(minimize, window)
```
--------------------------------
### Start HTTP Server with SSL
Source: https://pywebview.flowrl.com/examples/http_server.html
This snippet shows how to create a window and start the built-in HTTP server with SSL enabled. The server automatically handles local relative paths.
```python
import webview
if __name__ == '__main__':
webview.create_window('My first HTML5 application', 'assets/index.html')
# HTTP server is started automatically for local relative paths
webview.start(ssl=True)
```
--------------------------------
### Install pywebview with specific QT versions
Source: https://pywebview.flowrl.com/guide/installation.html
Install pywebview with different QT versions or bindings like PySide.
```bash
pip install pywebview[qt5]
```
```bash
pip install pywebview[pyside2]
```
```bash
pip install pywebview[pyside6]
```
--------------------------------
### Install pywebview with GTK support on Linux
Source: https://pywebview.flowrl.com/guide/installation.html
On Linux, explicitly install pywebview with GTK support if needed.
```bash
pip install pywebview[gtk]
```
--------------------------------
### Get Available Displays
Source: https://pywebview.flowrl.com/api.html
Returns a list of available displays, with the primary display listed first. This is useful for multi-monitor setups.
```python
webview.screens
```
--------------------------------
### Install legacy QtWebKit dependencies on Debian-based systems
Source: https://pywebview.flowrl.com/guide/installation.html
On Debian-based Linux systems, use apt to install legacy QtWebKit dependencies.
```bash
sudo apt install python3-pyqt5 python3-pyqt5.qtwebkit python-pyqt5 python-pyqt5.qtwebkit libqt5webkit5-dev
```
--------------------------------
### Install QT dependencies on Debian-based systems
Source: https://pywebview.flowrl.com/guide/installation.html
On Debian-based Linux systems, use apt to install QT dependencies for pywebview.
```bash
sudo apt install python3-pyqt5 python3-pyqt5.qtwebengine python3-pyqt5.qtwebchannel libqt5webkit5-dev
```
--------------------------------
### Install py-objc core and framework packages
Source: https://pywebview.flowrl.com/guide/installation.html
On macOS, if using a stand-alone Python installation, install these specific py-objc packages.
```bash
pyobjc-core
pyobjc-framework-Cocoa
pyobjc-framework-Quartz
pyobjc-framework-WebKit
pyobjc-framework-security
```
--------------------------------
### Install pywebview with optional dependencies
Source: https://pywebview.flowrl.com/guide/installation.html
Install pywebview with additional optional dependencies such as Android support, CEF, or SSL support.
```bash
pip install pywebview[android]
```
```bash
pip install pywebview[cef]
```
```bash
pip install pywebview[ssl]
```
--------------------------------
### Hello World with pywebview
Source: https://pywebview.flowrl.com/guide
Create a basic window with pywebview to display a given URL and start the application.
```python
import webview
webview.create_window('Hello world', 'https://pywebview.flowrl.com/')
webview.start()
```
--------------------------------
### Hello World with pywebview 3.0
Source: https://pywebview.flowrl.com/blog/pywebview3.html
Basic 'Hello World' example demonstrating the new API with webview.create_window() and webview.start().
```python
import webview
window = webview.create_window('Hello world', 'https://pywebview.flowrl.com/hello')
webview.start()
```
--------------------------------
### Install Pre-commit Hooks
Source: https://pywebview.flowrl.com/contributing/development.html
Install pre-commit hooks to automatically format and lint code before each commit. This ensures code quality standards are met.
```bash
pre-commit install
```
--------------------------------
### Hello World GUI
Source: https://pywebview.flowrl.com/3.7
Create a basic window with a title and load a URL. The webview must be started to display the window.
```python
import webview
webview.create_window('Hello world', 'https://pywebview.flowrl.com/')
webview.start()
```
--------------------------------
### Start GUI loop with thread-specific code
Source: https://pywebview.flowrl.com/blog/pywebview3.html
Execute thread-specific code after the GUI loop starts using webview.start() with a callback function.
```python
import webview
def change_title(window):
window.change_title('pywebview whoa')
window = webview.create_window('pywebview wow', 'https://pywebview.flowrl.com/hello')
webview.start(change_title, window)
```
--------------------------------
### Install PyGObject and GTK dependencies on Ubuntu
Source: https://pywebview.flowrl.com/guide/installation.html
On Ubuntu, use apt to install PyGObject and GTK dependencies for pywebview.
```bash
sudo apt install python3-gi python3-gi-cairo gir1.2-gtk-3.0 gir1.2-webkit2-4.1
```
--------------------------------
### webview.start
Source: https://pywebview.flowrl.com/api.html
Starts the GUI loop and displays created windows. This function must be called from the main thread and offers extensive customization through its parameters.
```APIDOC
## webview.start
### Description
Starts a GUI loop and displays previously created windows. This function must be called from a main thread.
### Parameters
#### Function Arguments
- **func** (function, optional) - Function to invoke upon starting the GUI loop.
- **args** (single value or tuple, optional) - Function arguments.
- **localization** (dict, optional) - A dictionary with localized strings. Default strings and their keys are defined in localization.py.
- **gui** (string, optional) - Force a specific GUI. Allowed values are `cef`, `qt` or `gtk` depending on a platform. See Web Engine for details.
- **debug** (bool, optional) - Enable debug mode. See Debugging for details. Defaults to False.
- **http_server** (bool, optional) - Enable built-in HTTP server for absolute local paths. For relative paths HTTP server is started automatically and cannot be disabled. For each window, a separate HTTP server is spawned. This option is ignored for non-local URLs.
- **http_port** (int, optional) - Specify a port number for the HTTP server. By default port is randomized.
- **user_agent** (string, optional) - Change user agent string.
- **private_mode** (bool, optional) - Control whether cookies and other persistant objects are stored between session. By default private mode is on and nothing is stored between sessions. Defaults to True.
- **storage_path** (string, optional) - An optional location on hard drive where to store persistant objects like cookies and local storage. By default `~/.pywebview` is used on *nix systems and `%APPDATA%\pywebview` on Windows.
- **menu** (list, optional) - Pass a list of Menu objects to create an application menu. See this example for usage details.
- **server** (WSGI server instance, optional) - A custom WSGI server instance. Defaults to BottleServer.
- **ssl** (bool, optional) - If using the default BottleServer (and for now the GTK backend), will use SSL encryption between the webview and the internal server. You need to have `cryptography` pip dependency installed in order to use `ssl`. It is not installed by default.
- **server_args** (dict, optional) - Dictionary of arguments to pass through to the server instantiation.
- **icon** (string, optional) - Path to application icon. Generally icon should be specified during bundling, but if you need to set it manually, you can use this parameter. Supported formats are `.ico` on Windows and `.icns` on macOS. On Linux support depends on the desktop environment, but generally `.png` icons are supported.
### Examples
* Simple window
* Multi-window
```
--------------------------------
### Install Python 3 with Homebrew
Source: https://pywebview.flowrl.com/guide/faq.html
On macOS, use Homebrew to install Python 3 to avoid potential keyboard focus issues with pywebview in virtual environments created with the built-in Python.
```bash
brew install python3
virtualenv pywebview_env -p python3
```
--------------------------------
### Set QT Renderer via Environment Variable
Source: https://pywebview.flowrl.com/guide/web_engine.html
This example shows how to force the QT renderer on Linux systems using an environment variable.
```bash
export PYWEBVIEW_GUI=qt
```
--------------------------------
### Create a Basic Webview Window
Source: https://pywebview.flowrl.com/examples/simple_browser.html
This snippet shows the minimal code required to create a webview window and load a URL. Ensure you have the webview library installed.
```python
import webview
if __name__ == '__main__':
# Create a standard webview window
window = webview.create_window('Simple browser', 'https://pywebview.flowrl.com/hello')
webview.start()
```
--------------------------------
### window.events.initialized
Source: https://pywebview.flowrl.com/api.html
Fired after GUI is chosen and HTTP server started. Returning `False` cancels window creation. This event is blocking.
```APIDOC
## window.events.initialized
### Description
The event is fired right after GUI is chosen and HTTP server is started (if applicable). The first parameter `renderer` has a value of the chosen GUI library / web renderer. If event handler returns False, the window creation will be cancelled and GUI loop will not be started (for windows created before the GUI loop is started). This event is blocking.
### Method
Event Subscription
### Endpoint
window.events.initialized
### Parameters
#### Event Handler Parameters
- **window** (object) - The window object.
- **renderer** (string) - The name of the chosen GUI library / web renderer.
### Request Example
```python
def handle_initialized(window, renderer):
print(f"Window initialized with renderer: {renderer}")
# return False # Uncomment to cancel window creation
window.events.initialized += handle_initialized
```
### Response
- **Boolean** - Returning `False` cancels window creation and prevents the GUI loop from starting.
```
--------------------------------
### webview.start Function Signature
Source: https://pywebview.flowrl.com/api.html
This is the function signature for webview.start, outlining all available parameters and their default values. It is used to start the GUI loop and display windows.
```python
webview.start(func=None, args=None, localization={}, gui=None, debug=False,
http_server=False, http_port=None, user_agent=None, private_mode=True,
storage_path=None, menu=[], server=http.BottleServer, ssl=False,
server_args={}, icon=None):
```
--------------------------------
### Get and Display Screen Information
Source: https://pywebview.flowrl.com/examples/screens.html
This snippet retrieves information about all available displays and prints their properties. It then creates a separate window on each detected screen.
```Python
import webview
if __name__ == '__main__':
screens = webview.screens
print('Available screens:')
for i, screen in enumerate(screens):
print(f'
Screen {i + 1}:')
print(f' Position: ({screen.x}, {screen.y})')
print(f' Size: {screen.width}x{screen.height}')
print(f' Scale: {screen.scale}x')
print(f' DPI: {screen.dpi}')
print(f' Physical Size: {screen.physical_width}x{screen.physical_height}')
webview.create_window('', html=f'placed on the monitor {i + 1}', screen=screen)
webview.start()
```
--------------------------------
### DOM Traversal Example
Source: https://pywebview.flowrl.com/examples/dom_traversal.html
This Python code snippet shows how to get DOM elements by ID and then traverse their relationships (children, parent, next, previous siblings) using pywebview. It's useful for dynamically interacting with web content rendered by pywebview.
```Python
import webview
def bind(window):
container = window.dom.get_element('#container')
container_button = window.dom.get_element('#container-button')
blue_rectangle = window.dom.get_element('#blue-rectangle')
blue_parent_button = window.dom.get_element('#blue-parent-button')
blue_next_button = window.dom.get_element('#blue-next-button')
blue_previous_button = window.dom.get_element('#blue-previous-button')
container_button.events.click += lambda e: print(container.children)
blue_parent_button.events.click += lambda e: print(blue_rectangle.parent)
blue_next_button.events.click += lambda e: print(blue_rectangle.next)
blue_previous_button.events.click += lambda e: print(blue_rectangle.previous)
if __name__ == '__main__':
window = webview.create_window(
'DOM Manipulations Example',
html="""
Container
RED
BLUE
GREEN
""",
)
webview.start(bind, window)
```
--------------------------------
### Multiple Server Example
Source: https://pywebview.flowrl.com/examples/multiple_servers.html
This snippet demonstrates creating multiple windows with independent servers. It uses Bottle to define web applications for different windows and shows how to access server information.
```python
import bottle
import webview
# We'll have a global list of our windows so our web app can give us information
# about them
windows = []
# A simple function to format a description of our servers
def serverDescription(server):
return f'{str(server).replace("<", "").replace(">", "")}'
# Define a couple of simple web apps using Bottle
app1 = bottle.Bottle()
@app1.route('/')
def hello():
return '
Second Window
This one is a web app and has its own server.
'
app2 = bottle.Bottle()
@app2.route('/')
def hello2():
head = """
"""
body = f"""
Third Window
This one is another web app and has its own server. It was started after webview.start.
Server Descriptions:
Window
Object
IP Address
Global Server
{serverDescription(webview.http.global_server)}
{webview.http.global_server.address if webview.http.global_server is not None else 'None'}
First Window
{serverDescription(windows[0]._server)}
{windows[0]._server.address if windows[0]._server is not None else 'None'}
Second Window
{serverDescription(windows[1]._server)}
{windows[1]._server.address}
Third Window
{serverDescription(windows[2]._server)}
{windows[2]._server.address}
"""
return head + body
def third_window():
# Create a new window after the loop started
windows.append(webview.create_window('Window #3', url=app2))
if __name__ == '__main__':
# Master window
windows.append(
webview.create_window(
'Window #1',
html='
First window
This one is static HTML and just uses the global server for api calls.',
)
)
windows.append(webview.create_window('Window #2', url=app1, http_port=3333))
webview.start(third_window, http_server=True, http_port=3334)
```
--------------------------------
### Set QT Renderer via webview.start()
Source: https://pywebview.flowrl.com/guide/web_engine.html
This Python code snippet demonstrates how to specify the QT renderer when initiating the webview.
```python
import webview
webview.start(gui='qt')
```
--------------------------------
### Set CEF Renderer via Environment Variable
Source: https://pywebview.flowrl.com/guide/web_engine.html
Use this method to set the CEF renderer for pywebview on Windows before starting the application.
```bash
export PYWEBVIEW_GUI=cef
```
--------------------------------
### Hide and Show Window Example
Source: https://pywebview.flowrl.com/examples/hide_window.html
This Python snippet shows how to create a window that is initially hidden and then control its visibility using the `show()` and `hide()` methods. It requires the `webview` and `time` modules.
```Python
import time
import webview
def hide_show(window):
print('Window is started hidden')
time.sleep(5)
print('Showing window')
window.show()
time.sleep(5)
print('Hiding window')
window.hide()
time.sleep(5)
print('And showing again')
window.show()
if __name__ == '__main__':
window = webview.create_window(
'Hide / show window', 'https://pywebview.flowrl.com/hello', hidden=True
)
webview.start(hide_show, window)
```
--------------------------------
### Start HTTP Server with SSL
Source: https://pywebview.flowrl.com/guide/usage.html
Launches a pywebview window and enables SSL for the internal Bottle.py HTTP server. This is useful for serving local files securely.
```python
import webview
webview.create_window('Woah dude!', 'src/index.html')
webview.start(ssl=True)
```
--------------------------------
### State Management Example
Source: https://pywebview.flowrl.com/examples/state.html
This snippet shows how to initialize, update, and listen for changes to the state object. It includes Python code for backend logic and HTML/JavaScript for the frontend interface. Use this to synchronize data between Python and JavaScript.
```python
import webview
html = """
State
Counter value: 0
"""
def on_counter_change(type, key, value):
print(f'Event {type} for {key} value : {value}')
def decrease_counter():
window.state.counter -= 1
def on_loaded(window):
window.expose(decrease_counter)
window.state += on_counter_change
if __name__ == '__main__':
global window
window = webview.create_window('State example', html=html)
window.state.counter = 0
window.events.loaded += on_loaded
webview.start(debug=True)
```
--------------------------------
### element.attributes
Source: https://pywebview.flowrl.com/api.html
Get or modify an element's attributes. This property returns a PropsDict-like object that allows for setting, getting, and removing attributes.
```APIDOC
## element.attributes
### Description
Get or modify element's attributes. `attributes` is a `PropsDict` dict-like object that implements most of dict functions. To add an attribute, you can simply assign a value to a key in `attributes`. Similarly, to remove an attribute, you can set its value to None.
### Examples
```python
element.attributes['id'] = 'container-id' # set element's id
element.attributes['data-flag'] = '1337'
element.attributes['id'] = None # remove element's id
del element.attributes['data-flag'] # remove element's data-flag attribute
```
```
--------------------------------
### Get Display Scale Factor
Source: https://pywebview.flowrl.com/api.html
Access the `scale` property to get the display's scale factor (DPI scale). A value of 2.0 indicates a HiDPI display.
```python
screen.scale
```
--------------------------------
### Get DOM Elements by Selector
Source: https://pywebview.flowrl.com/examples/get_elements.html
Use `window.dom.get_elements` to retrieve DOM elements by CSS selectors. This snippet shows how to get elements by ID and class name, and then access their outer HTML.
```Python
import webview
def get_elements(window):
heading = window.dom.get_elements('#heading')
content = window.dom.get_elements('.content')
print(f'Heading:\n {heading[0].node["outerHTML"]}')
print(f'Content 1:\n {content[0].node["outerHTML"]}')
print(f'Content 2:\n {content[1].node["outerHTML"]}')
if __name__ == '__main__':
html = """
Heading
Content 1
Content 2
"
window = webview.create_window('Get elements example', html=html)
webview.start(get_elements, window)
```
--------------------------------
### Create Window with SSL Enabled
Source: https://pywebview.flowrl.com/examples/localhost_ssl.html
This snippet shows how to create a pywebview window and start the server with SSL enabled. Ensure you have the necessary SSL certificates configured for your local environment.
```python
import webview
if __name__ == '__main__':
webview.create_window('Local SSL Test', 'assets/index.html')
webview.start(ssl=True)
```
--------------------------------
### webview.dom.DOMEventHandler
Source: https://pywebview.flowrl.com/api.html
A container for an event handler used to control propagation or default behaviour of the event. If `debounce` is greater than zero, Python event handler is debounced by a specified number of milliseconds. This can be useful for events like `dragover` and `mouseover` that generate a constant stream of events resulting in poor performance. `DOMEventHandler` can be used to get a full path of droppped files in `drop` event on the Python side. The file path information is stored in `event['dataTransfer']['files'][0]['pywebviewFullPath']` property of the event object. See this example for details.
```APIDOC
### webview.dom.DOMEventHandler
A container for an event handler used to control propagation or default behaviour of the event. If `debounce` is greater than zero, Python event handler is debounced by a specified number of milliseconds. This can be useful for events like `dragover` and `mouseover` that generate a constant stream of events resulting in poor performance.
`DOMEventHandler` can be used to get a full path of droppped files in `drop` event on the Python side. The file path information is stored in `event['dataTransfer']['files'][0]['pywebviewFullPath']` property of the event object. See this example for details.
#### Examples
```
element.events.click += DOMEventHandler(on_click, prevent_default=True, stop_propagation=True, stop_immediate_propagation=True)
element.events.mouseover += DOMEventHandler(on_click, debounce=500)
```
```
--------------------------------
### Manage Multiple Windows and Active Window
Source: https://pywebview.flowrl.com/guide/usage.html
Demonstrates how to create multiple windows and access information about them, including the active window. The `shown` event is used to trigger a handler function when a window is displayed.
```python
import webview
def handler():
print(f'There are {len(webview.windows)} windows')
print(f'Active window: {webview.active_window().title}')
first_window = webview.create_window('pywebview docs', 'https://pywebview.flowrl.com')
second_window = webview.create_window('Woah dude!', 'https://woot.fi')
second_window.events.shown += handler
webview.start()
```
--------------------------------
### DOM Manipulation Example
Source: https://pywebview.flowrl.com/blog/pywebview5.html
Perform DOM manipulation, traversal, and event handling directly from Python using the new Element object. This example demonstrates event binding, style modification, attribute updates, and class toggling.
```python
window.dom.document.events.scroll += lambda e: print(window.dom.window.node['scrollY'])
button = window.dom.create_element('', window.dom.body)
button.style['width'] = '200px'
button.attributes = { 'disabled': False }
button.events.click += click_handler
button.classes.toggle('hidden')
```
--------------------------------
### window.title
Source: https://pywebview.flowrl.com/api.html
Get or set the title of the window.
```APIDOC
## window.title
### Description
Get or set the title of the window.
### Usage
```python
window.title = "New Title"
print(window.title)
```
```
--------------------------------
### window.get_current_url
Source: https://pywebview.flowrl.com/api.html
Get the current URL loaded in the window.
```APIDOC
## window.get_current_url()
### Description
Return the current URL. Returns `None` if no URL is loaded.
### Usage
```python
current_url = window.get_current_url()
print(current_url)
```
```
--------------------------------
### Open File Dialog Example
Source: https://pywebview.flowrl.com/examples/open_file_dialog.html
This snippet shows how to create an open file dialog that allows multiple file selections. It defines specific image file types and a general 'all files' option. Use this when you need to let users select one or more files from their system.
```python
import webview
def open_file_dialog(window):
file_types = ('Image Files (*.bmp;*.jpg;*.gif)', 'All files (*.*)')
result = window.create_file_dialog(
webview.FileDialog.OPEN, allow_multiple=True, file_types=file_types
)
print(result)
if __name__ == '__main__':
window = webview.create_window('Open file dialog example', 'https://pywebview.flowrl.com/hello')
webview.start(open_file_dialog, window)
```
--------------------------------
### window.height
Source: https://pywebview.flowrl.com/api.html
Get the height of the window in logical pixels.
```APIDOC
## window.height
### Description
Get the height of the window in logical pixels.
### Usage
```python
height = window.height
```
```
--------------------------------
### window.width
Source: https://pywebview.flowrl.com/api.html
Get the width of the window in logical pixels.
```APIDOC
## window.width
### Description
Get the width of the window in logical pixels.
### Usage
```python
width = window.width
```
```
--------------------------------
### screen.physical_height
Source: https://pywebview.flowrl.com/api.html
Get display height in physical pixels.
```APIDOC
## screen.physical_height
### Description
Get display height in physical pixels. Equal to `height * scale`.
### Code
screen.physical_height
```
--------------------------------
### Create window and load HTML directly via parameter
Source: https://pywebview.flowrl.com/blog/pywebview3.html
Create a window and load HTML content directly using the 'html' parameter in webview.create_window(). HTML content takes precedence over the 'url' parameter.
```python
import webview
window = webview.create_window('pywebview wow', html='
pywebview wow!
')
webview.start()
```
--------------------------------
### pywebview Event Handling Example
Source: https://pywebview.flowrl.com/examples/events.html
This snippet shows how to define and subscribe to various pywebview events. It covers window lifecycle events like closed, closing, before_show, shown, and initialized, as well as user interaction events such as loaded, minimized, restored, maximized, resized, and moved. It also demonstrates how to unsubscribe from an event.
```python
import webview
def on_before_show(window):
print('Native window object', window.native)
def on_closed():
print('pywebview window is closed')
def on_closing():
print('pywebview window is closing')
def on_initialized(renderer):
# return False to cancel initialization
print(f'GUI is initialized with renderer: {renderer}')
def on_shown():
print('pywebview window shown')
def on_minimized():
print('pywebview window minimized')
def on_restored():
print('pywebview window restored')
def on_maximized():
print('pywebview window maximized')
def on_resized(width, height):
print(f'pywebview window is resized. new dimensions are {width} x {height}')
# you can supply optional window argument to access the window object event was triggered on
def on_loaded(window):
print('DOM is ready')
# unsubscribe event listener
window.events.loaded -= on_loaded
window.load_url('https://pywebview.flowrl.com/hello')
def on_moved(x, y):
print(f'pywebview window is moved. new coordinates are x: {x}, y: {y}')
if __name__ == '__main__':
window = webview.create_window(
'Simple browser', 'https://pywebview.flowrl.com/', confirm_close=True
)
window.events.closed += on_closed
window.events.closing += on_closing
window.events.before_show += on_before_show
window.events.initialized += on_initialized
window.events.shown += on_shown
window.events.loaded += on_loaded
window.events.minimized += on_minimized
window.events.maximized += on_maximized
window.events.restored += on_restored
window.events.resized += on_resized
window.events.moved += on_moved
webview.start()
```
--------------------------------
### screen.physical_width
Source: https://pywebview.flowrl.com/api.html
Get display width in physical pixels.
```APIDOC
## screen.physical_width
### Description
Get display width in physical pixels. Equal to `width * scale`.
### Code
screen.physical_width
```
--------------------------------
### screen.width
Source: https://pywebview.flowrl.com/api.html
Get display width in logical pixels.
```APIDOC
## screen.width
### Description
Get display width in logical pixels.
### Code
screen.width
```
--------------------------------
### Create a Frameless Window
Source: https://pywebview.flowrl.com/examples/frameless.html
Creates a frameless and resizable webview window with minimum size constraints. The window can be moved by dragging any point within it due to easy_drag being enabled.
```python
import webview
if __name__ == '__main__':
# Create a resizable webview window with minimum size constraints
webview.create_window(
'Frameless window', 'http://pywebview.flowrl.com/hello', frameless=True, easy_drag=True
)
webview.start()
```
--------------------------------
### screen.height
Source: https://pywebview.flowrl.com/api.html
Get display height in logical pixels.
```APIDOC
## screen.height
### Description
Get display height in logical pixels.
### Code
screen.height
```
--------------------------------
### element.text
Source: https://pywebview.flowrl.com/api.html
Get or set the text content of an element.
```APIDOC
## element.text
### Description
Get or set element's text content.
### Code
```python
element.text
```
```
--------------------------------
### Py2app Setup Script for Pywebview
Source: https://pywebview.flowrl.com/examples/py2app_setup.html
Use this script with `python setup.py py2app` to freeze your pywebview application. It configures the application entry point, includes necessary modules, and specifies data files to be bundled.
```python
import os
from setuptools import setup
def tree(src):
return [
(root, map(lambda f: os.path.join(root, f), files))
for (root, dirs, files) in os.walk(os.path.normpath(src))
]
ENTRY_POINT = ['simple_browser.py']
DATA_FILES = tree('DATA_FILES_DIR') + tree('DATA_FILE_DIR2')
OPTIONS = {
'argv_emulation': False,
'strip': True,
'#iconfile': 'icon.icns', # uncomment to include an icon
'includes': ['WebKit', 'Foundation', 'webview'],
}
setup(
app=ENTRY_POINT,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
```
--------------------------------
### window.on_top
Source: https://pywebview.flowrl.com/api.html
Get or set whether the window is always on top.
```APIDOC
## window.on_top
### Description
Get or set whether the window is always on top.
### Usage
```python
window.on_top = True
print(window.on_top)
```
```
--------------------------------
### Execute Backend Logic in a Separate Thread
Source: https://pywebview.flowrl.com/guide/usage.html
Shows how to execute custom backend logic concurrently with the GUI loop by passing a function to `webview.start`. This allows for operations like toggling fullscreen or executing JavaScript in the window.
```python
import webview
def custom_logic(window):
window.toggle_fullscreen()
window.evaluate_js('alert("Nice one brother")')
window = webview.create_window('Woah dude!', html='
Woah dude!
')
webview.start(custom_logic, window)
# anything below this line will be executed after program is finished executing
pass
```
--------------------------------
### webview.create_window
Source: https://pywebview.flowrl.com/api.html
Creates a new GUI window with customizable properties and returns its instance. This function allows for detailed configuration of window appearance and behavior.
```APIDOC
## webview.create_window
### Description
Create a new _pywebview_ window and returns its instance. Can be used to create multiple windows (except Android). Window is not shown until the GUI loop is started. If the function is invoked during the GUI loop, the window is displayed immediately.
### Method
POST (Implicit)
### Endpoint
N/A (Python function call)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **title** (string) - Required - Window title
- **url** (string) - Optional - URL to load. If the URL does not have a protocol prefix, it is resolved as a path relative to the application entry point. Alternatively a WSGI server object can be passed to start a local web server.
- **html** (string) - Optional - HTML code to load. If both URL and HTML are specified, HTML takes precedence.
- **js_api** (object) - Optional - Expose a python object to the Javascript domain of the current `pywebview` window. Methods of the `js_api` object can be invoked from Javascript by calling `window.pywebview.api.()` functions. Exposed function return a promise that return once function returns. Only basic Python objects (like int, str, dict, ...) can be returned to Javascript.
- **width** (integer) - Optional - Window width in logical pixels. Default is 800px.
- **height** (integer) - Optional - Window height in logical pixels. Default is 600px.
- **x** (integer) - Optional - Window x coordinate in logical pixels. Default is centered.
- **y** (integer) - Optional - Window y coordinate in logical pixels. Default is centered.
- **screen** (object) - Optional - Screen to display window on. `screen` is a screen instance returned by `webview.screens`.
- **resizable** (boolean) - Optional - Whether window can be resized. Default is True
- **fullscreen** (boolean) - Optional - Start in fullscreen mode. Default is False
- **min_size** (tuple) - Optional - a (width, height) tuple that specifies a minimum window size in logical pixels. Default is 200x100
- **hidden** (boolean) - Optional - Create a window hidden by default. Default is False
- **frameless** (boolean) - Optional - Create a frameless window. Default is False.
- **easy_drag** (boolean) - Optional - Easy drag mode for frameless windows. Window can be moved by dragging any point. Default is True. Note that easy_drag has no effect with normal windows. To control dragging on an element basis, see drag area for details.
- **shadow** (boolean) - Optional - Add window shadow. Default is False. _Windows only_.
- **focus** (boolean) - Optional - Create a non-focusable window if False. Default is True.
- **minimized** (boolean) - Optional - Display window minimized
- **maximized** (boolean) - Optional - Display window maximized
- **menu** (list) - Optional - A list of `Menu` objects to create a window specific menu. This menu overrides the application menu specified in `webview.start`. Not supported on GTK.
- **on_top** (boolean) - Optional - Set window to be always on top of other windows. Default is False.
- **confirm_close** (boolean) - Optional - Whether to display a window close confirmation dialog. Default is False
- **background_color** (string) - Optional - Background color of the window displayed before WebView is loaded. Specified as a hex color. Default is white.
- **transparent** (boolean) - Optional - Create a transparent window. Not supported on Windows. Default is False. Note that this setting does not hide or make window chrome transparent. To hide window chrome set `frameless` to True.
- **text_select** (boolean) - Optional - Enables document text selection. Default is False. To control text selection on per element basis, use user-select CSS property.
- **zoomable** (boolean) - Optional - Enable document zooming. Default is False
- **draggable** (boolean) - Optional - Enable image and link object dragging. Default is False
- **vibrancy** (boolean) - Optional - Enable window vibrancy. Default is False. macOS only.
- **server** (object) - Optional - A custom WSGI server instance for this window. Defaults to BottleServer.
- **server_args** (dict) - Optional - Dictionary of arguments to pass through to the server instantiation
- **localization** (dict) - Optional - pass a localization dictionary for per window localization.
### Request Example
```json
{
"title": "My App",
"url": "http://localhost:8080",
"width": 1024,
"height": 768
}
```
### Response
#### Success Response (200)
- **window_instance** (object) - An instance of the newly created window.
#### Response Example
```json
{
"window_instance": ""
}
```
```
--------------------------------
### Get Window Title
Source: https://pywebview.flowrl.com/api.html
Retrieve the current title of the window.
```python
window.title
```
--------------------------------
### screen.dpi
Source: https://pywebview.flowrl.com/api.html
Get the DPI (dots per inch) for this display.
```APIDOC
## screen.dpi
### Description
Get the DPI (dots per inch) for this display. Calculated as `scale * 96`. Standard DPI is 96, so a 2x scaled display would report 192 DPI.
### Code
screen.dpi
```
--------------------------------
### screen.scale
Source: https://pywebview.flowrl.com/api.html
Get the scale factor (DPI scale) for this display.
```APIDOC
## screen.scale
### Description
Get the scale factor (DPI scale) for this display. For example, a value of `2.0` indicates a Retina or HiDPI display with 2x scaling, while `1.0` indicates a standard DPI display.
### Code
screen.scale
```
--------------------------------
### Python Confirmation Dialog Example
Source: https://pywebview.flowrl.com/examples/confirmation_dialog.html
Use `window.create_confirmation_dialog` to display a modal dialog with a question and OK/Cancel buttons. The function returns `True` if the user clicks OK, and `False` if they click Cancel.
```python
import webview
def open_confirmation_dialog(window):
result = window.create_confirmation_dialog('Question', 'Are you ok with this?')
if result:
print('User clicked OK')
else:
print('User clicked Cancel')
if __name__ == '__main__':
window = webview.create_window(
'Confirmation dialog example', 'https://pywebview.flowrl.com/hello'
)
webview.start(open_confirmation_dialog, window)
```
--------------------------------
### Creating Application Menus in pywebview
Source: https://pywebview.flowrl.com/examples/menu.html
This snippet shows how to define a complex application menu structure, including macOS-specific app menus, standard menus with actions, separators, and submenus. It also demonstrates creating multiple windows with different menu configurations.
```python
import webview
from webview.menu import Menu, MenuAction, MenuSeparator
def change_active_window_content():
active_window = webview.active_window()
if active_window:
active_window.load_html('
You changed this window!
')
def click_me():
active_window = webview.active_window()
if active_window:
active_window.load_html('
You clicked me!
')
def test():
active_window = webview.active_window()
if active_window:
active_window.load_html('
'
)
if __name__ == '__main__':
# App menu items (macOS only - appears between About and Services)
# On other platforms, this menu is ignored
macos_app_menu = Menu(
'__app__',
[
MenuAction('Preferences...', open_preferences),
MenuSeparator(),
MenuAction('Check for Updates', check_for_updates),
],
)
window_menu = [Menu('Window', [MenuAction('Test', test)])]
app_menu = [
macos_app_menu, # macOS app menu items
Menu(
'Menu 1',
[
MenuAction('Change Active Window Content', change_active_window_content),
MenuSeparator(),
Menu(
'Random',
[
MenuAction('Click Me', click_me),
MenuAction('File Dialog', open_save_file_dialog),
],
),
],
),
Menu('Menu 2', [MenuAction('This will do nothing', do_nothing)]),
]
window_1 = webview.create_window(
'Application Menu Example', 'https://pywebview.flowrl.com/hello'
)
window_2 = webview.create_window(
'Window Menu Example',
html='
Another window to test application menu
',
menu=window_menu,
)
webview.start(menu=app_menu)
```
--------------------------------
### Get Element Tabindex
Source: https://pywebview.flowrl.com/api.html
Retrieve the tabindex attribute of an element.
```python
element.tabindex
```
--------------------------------
### Create Window with External URL
Source: https://pywebview.flowrl.com/guide/architecture.html
Point directly to a URL to load content. This requires a running web server, either local or remote.
```python
webview.create_window('Simple browser', 'https://pywebview.flowrl.com')
webview.start()
```
--------------------------------
### window.y
Source: https://pywebview.flowrl.com/api.html
Get the Y coordinate of the top-left corner of the window in logical pixels.
```APIDOC
## window.y
### Description
Get the Y coordinate of the top-left corner of the window in logical pixels. For macOS, the Y-coordinate is measured from the bottom of the screen but is converted to a coordinate system with Y=0 at the top of the screen for consistency with other platforms.
### Usage
```python
y_coordinate = window.y
```
```