### Install TkinterWeb with Recommended Extras
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/usage.rst
Install TkinterWeb with the recommended set of optional dependencies using pip.
```console
$ pip install tkinterweb[recommended]
```
--------------------------------
### Run TkinterWeb Demo
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/usage.rst
Launch the TkinterWeb demo application to verify the installation.
```python
from tkinterweb import Demo
Demo()
```
--------------------------------
### Install TkinterWeb with Specific Extras
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/usage.rst
Install TkinterWeb with a specific selection of optional dependencies.
```console
$ pip install tkinterweb[html,images,svg,javascript,requests]
```
--------------------------------
### Install TkinterWeb with Extras
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Install TkinterWeb using pip, with options for recommended or full extras, or individual components.
```bash
pip install tkinterweb[recommended]
# or for everything
pip install tkinterweb[full]
# individual extras: html, images, svg, javascript, requests
```
--------------------------------
### Install PythonMonkey for JavaScript Support
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/javascript.rst
Install the PythonMonkey library using pip to enable JavaScript support in TkinterWeb. Alternatively, install TkinterWeb with the javascript extra.
```console
$ pip install pythonmonkey
```
```console
$ pip install tkinterweb[javascript]
```
--------------------------------
### Basic HtmlFrame Widget Usage
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Demonstrates creating an HtmlFrame widget, loading HTML content, and binding to common events. Ensure Tkinter and TkinterWeb are installed.
```python
import tkinter as tk
from tkinterweb import HtmlFrame
from tkinterweb.utilities import (
DONE_LOADING_EVENT, DOWNLOADING_RESOURCE_EVENT,
URL_CHANGED_EVENT, TITLE_CHANGED_EVENT, DOM_CONTENT_LOADED_EVENT,
)
root = tk.Tk()
root.title("TkinterWeb Demo")
# --- Create the widget with common options ---
frame = HtmlFrame(
root,
messages_enabled=True, # print debug messages
vertical_scrollbar="dynamic", # show scrollbar only when needed
horizontal_scrollbar=False,
zoom=1.0, # page zoom multiplier
fontscale=1.0, # text-only zoom
javascript_enabled=False, # enable JS (requires PythonMonkey)
dark_theme_enabled=False, # auto dark mode
images_enabled=True,
forms_enabled=True,
selection_enabled=True,
caret_browsing_enabled=False,
on_navigate_fail=lambda url, err, code: print(f"Error {code}: {err}"),
on_link_click=lambda url: frame.load_url(url),
on_form_submit=lambda url, data, method: frame.load_form_data(url, data, method),
)
frame.pack(fill="both", expand=True)
# --- Loading content ---
frame.load_html("
Hello, World!
TkinterWeb rocks.
")
frame.load_url("https://example.com")
frame.load_file("/path/to/page.html")
frame.load_website("example.com") # auto-adds http://
frame.load_form_data("https://httpbin.org/post", "key=value", "POST")
# --- Event bindings (virtual events) ---
frame.bind(DONE_LOADING_EVENT, lambda e: print("Done loading"))
frame.bind(DOWNLOADING_RESOURCE_EVENT, lambda e: print("Loading…"))
frame.bind(URL_CHANGED_EVENT, lambda e: print("URL:", frame.current_url))
frame.bind(TITLE_CHANGED_EVENT, lambda e: root.title(frame.title))
frame.bind(DOM_CONTENT_LOADED_EVENT, lambda e: print("DOM ready"))
# --- Read-only properties ---
print(frame.title) # document title
print(frame.icon) # favicon URL
print(frame.current_url) # current URL
print(frame.base_url) # resolved base URL
root.mainloop()
```
--------------------------------
### Basic TkinterWeb HtmlFrame Example
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/usage.rst
Embed an HtmlFrame widget in a Tkinter window and load basic HTML content.
```python
import tkinter as tk
from tkinterweb import HtmlFrame # import the HtmlFrame widget
root = tk.Tk() # create the Tkinter window
yourhtmlframe = HtmlFrame(root, messages_enabled=True) # create the HtmlFrame widget
yourhtmlframe.load_html("
Hello, World!
") # load some HTML code
yourhtmlframe.pack(fill="both", expand=True) # attach the HtmlFrame widget to the window
root.mainloop()
```
--------------------------------
### Inspect Hovered Elements and Resolve URLs with HtmlFrame
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Shows how to get the currently hovered HTML element, extract its attributes like 'href', and resolve relative URLs to absolute paths using HtmlFrame. Also demonstrates creating a context menu on right-click.
```python
import tkinter as tk
from tkinterweb import HtmlFrame
root = tk.Tk()
frame = HtmlFrame(root, on_link_click=lambda url: None)
frame.pack(fill="both", expand=True)
frame.load_html('About | Hover me')
def on_motion(event):
element = frame.get_currently_hovered_element()
if element:
href = element.getAttribute("href")
if href:
full_url = frame.resolve_url(href)
print("Link URL:", full_url)
def on_right_click(event):
element = frame.get_currently_hovered_element()
if element:
menu = tk.Menu(root, tearoff=0)
menu.add_command(label=f"Tag: {element.tagName}")
menu.tk_popup(event.x_root, event.y_root)
frame.bind("", on_motion)
frame.bind("", on_right_click)
root.mainloop()
```
--------------------------------
### Manage Text Selection with HtmlFrame
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Programmatically get, set, and clear text selections within the HtmlFrame. Requires `selection_enabled=True` during initialization.
```python
import tkinter as tk
from tkinterweb import HtmlFrame
root = tk.Tk()
frame = HtmlFrame(root, selection_enabled=True)
frame.pack(fill="both", expand=True)
frame.load_html("
Select some of this interesting text here.
")
def on_button():
# Get selected string
text = frame.get_selection()
print("Selected:", text)
# Get selection with element + index info
result = frame.get_selection_position(return_elements=True)
if result:
(start_el, start_text, start_idx), (end_el, end_text, end_idx), middle = result
print(f"Start at index {start_idx} in '{start_text}'")
# Programmatically select characters 0–9 of the page text
frame.set_selection_position(start_index=0, end_index=9)
# Select all
frame.select_all()
# Clear
frame.clear_selection()
tk.Button(root, text="Selection info", command=on_button).pack()
root.mainloop()
```
--------------------------------
### HtmlFrame Position Method Updates (Version 4.16)
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/upgrading.rst
In version 4.16, methods related to getting and setting caret and selection positions on `HtmlFrame` were updated to use new parameter options.
```APIDOC
## HtmlFrame Position Method Updates
### Description
Methods for managing caret and selection positions have been updated with new parameter behaviors.
### Methods
- `:meth:`.HtmlFrame.get_caret_page_position` - Use `:meth:HtmlFrame.get_caret_position(return_element=False)`
- `:meth:`.HtmlFrame.set_caret_page_position` - Use `:meth:HtmlFrame.set_caret_position(index=)`
- `:meth:`.HtmlFrame.get_selection_page_position` - Use `:meth:HtmlFrame.get_selection_position(return_elements=False)`
- `:meth:`.HtmlFrame.set_selection_page_position` - Use `:meth:HtmlFrame.set_selection_position(start_index=, end_index=)
```
--------------------------------
### Displaying a Website with HtmlFrame in Tkinter
Source: https://github.com/andereoo/tkinterweb/blob/main/README.md
Use this snippet to integrate an HtmlFrame widget into your Tkinter application to load and display web content. Ensure Tkinter and tkinterweb are installed.
```python
import tkinter as tk
from tkinterweb import HtmlFrame # import the HtmlFrame widget
root = tk.Tk() # create the Tkinter window
frame = HtmlFrame(root, messages_enabled=True) # create the HtmlFrame widget
frame.load_website("https://tkinterweb.readthedocs.io/en/latest/index.html") # load a website
frame.pack(fill="both", expand=True) # attach the HtmlFrame widget to the window
root.mainloop()
```
--------------------------------
### HtmlFrame Configuration and Runtime Control
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Shows how to configure HtmlFrame options at runtime using the `configure` method and how to retrieve option values using `cget`. Also demonstrates `reload` and `stop` methods.
```APIDOC
## HtmlFrame Configuration and Runtime Control
### Description
Demonstrates how to configure `HtmlFrame` options at runtime using the `configure` method, retrieve option values using `cget`, and control rendering with `reload` and `stop`.
### Method
```python
import tkinter as tk
from tkinterweb import HtmlFrame
root = tk.Tk()
frame = HtmlFrame(root)
frame.pack(fill="both", expand=True)
frame.load_url("https://example.com")
# Change options at runtime
frame.configure(zoom=1.5)
frame.configure(fontscale=1.2)
frame.configure(dark_theme_enabled=True)
frame.configure(images_enabled=False)
frame.configure(
find_match_highlight_color="#f1a1f7",
find_match_text_color="#000",
find_current_highlight_color="#8bf0b3",
selected_text_highlight_color="#9bc6fa",
)
frame.configure(headers={"User-Agent": "MyApp/1.0"})
frame.configure(request_timeout=30)
frame.configure(insecure_https=True) # ignore certificate errors
# Read a value
zoom = frame.cget("zoom") # or frame["zoom"]
print(zoom)
# Reload and stop
frame.reload()
frame.stop()
root.mainloop()
```
```
--------------------------------
### HtmlFrame Widget Initialization and Content Loading
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Demonstrates how to initialize the HtmlFrame widget with various options and load content using different methods like load_html, load_url, load_file, and load_website.
```APIDOC
## HtmlFrame Initialization and Content Loading
### Description
Initializes the `HtmlFrame` widget with common options and demonstrates various methods for loading HTML content.
### Method
```python
import tkinter as tk
from tkinterweb import HtmlFrame
from tkinterweb.utilities import (
DONE_LOADING_EVENT,
DOWNLOADING_RESOURCE_EVENT,
URL_CHANGED_EVENT,
TITLE_CHANGED_EVENT,
DOM_CONTENT_LOADED_EVENT,
)
root = tk.Tk()
root.title("TkinterWeb Demo")
# --- Create the widget with common options ---
frame = HtmlFrame(
root,
messages_enabled=True, # print debug messages
vertical_scrollbar="dynamic", # show scrollbar only when needed
horizontal_scrollbar=False,
zoom=1.0, # page zoom multiplier
fontscale=1.0, # text-only zoom
javascript_enabled=False, # enable JS (requires PythonMonkey)
dark_theme_enabled=False, # auto dark mode
images_enabled=True,
forms_enabled=True,
selection_enabled=True,
caret_browsing_enabled=False,
on_navigate_fail=lambda url, err, code: print(f"Error {code}: {err}"),
on_link_click=lambda url: frame.load_url(url),
on_form_submit=lambda url, data, method: frame.load_form_data(url, data, method),
)
frame.pack(fill="both", expand=True)
# --- Loading content ---
frame.load_html("
Hello, World!
TkinterWeb rocks.
")
frame.load_url("https://example.com")
frame.load_file("/path/to/page.html")
frame.load_website("example.com") # auto-adds http://
frame.load_form_data("https://httpbin.org/post", "key=value", "POST")
# --- Event bindings (virtual events) ---
frame.bind(DONE_LOADING_EVENT, lambda e: print("Done loading"))
frame.bind(DOWNLOADING_RESOURCE_EVENT, lambda e: print("Loading…"))
frame.bind(URL_CHANGED_EVENT, lambda e: print("URL:", frame.current_url))
frame.bind(TITLE_CHANGED_EVENT, lambda e: root.title(frame.title))
frame.bind(DOM_CONTENT_LOADED_EVENT, lambda e: print("DOM ready"))
# --- Read-only properties ---
print(frame.title) # document title
print(frame.icon) # favicon URL
print(frame.current_url) # current URL
print(frame.base_url) # resolved base URL
root.mainloop()
```
```
--------------------------------
### Launch TkinterWeb Demo
Source: https://context7.com/andereoo/tkinterweb/llms.txt
The `Demo` class launches a self-contained browser that displays the TkinterWeb documentation site. An internet connection is required for this demonstration.
```python
from tkinterweb import Demo
Demo() # opens a Tkinter window browsing tkinterweb.readthedocs.io
```
--------------------------------
### Demo Class
Source: https://context7.com/andereoo/tkinterweb/llms.txt
The `Demo` class launches a self-contained browser that displays the TkinterWeb documentation site. This feature requires an active internet connection to load the documentation.
```APIDOC
## Demo — built-in interactive demonstration
`Demo` launches a self-contained browser displaying the TkinterWeb documentation site. It requires an internet connection.
```python
from tkinterweb import Demo
Demo() # opens a Tkinter window browsing tkinterweb.readthedocs.io
```
```
--------------------------------
### Save Page, Snapshot, and Screenshot with HtmlFrame
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Demonstrates saving the HTML source, a rendered snapshot, and a screenshot of a loaded webpage using HtmlFrame. Requires PIL for screenshots.
```python
import tkinter as tk
from tkinterweb import HtmlFrame
root = tk.Tk()
frame = HtmlFrame(root)
frame.pack(fill="both", expand=True)
frame.load_url("https://example.com")
def after_load(event):
# Save original HTML source
html_source = frame.save_page("page.html")
# Save rendered snapshot (inlined CSS, no external links)
snapshot = frame.snapshot_page("snapshot.html", allow_agent=False)
# Get page plain-text
text = frame.get_page_text()
print(text[:200])
# Screenshot (requires PIL)
img = frame.screenshot_page("screenshot.png", full=False, show=False)
print(img.size)
# Print to PostScript (requires experimental=True)
# ps = frame.print_page("page.ps", pagesize="A4")
frame.bind("<>", after_load)
root.mainloop()
```
--------------------------------
### Register Python Object for JavaScript Access
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/javascript.rst
Register a Python function to be accessible from JavaScript code within the TkinterWeb document. This allows JavaScript to call Python functions, for example, to implement custom alert dialogs.
```python
yourhtmlframe = tkinterweb.HtmlFrame(root, messages_enabled=True, javascript_enabled=True)
def open_alert_window(text):
## Do stuff
yourhtmlframe.javascript.register("alert", open_alert_window)
yourhtmlframe.load_html("
Hello, world!
")
```
--------------------------------
### Create Styled Labels with HtmlLabel
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Shows how to create simple and rich HTML labels using the HtmlLabel widget, which inherits methods from HtmlFrame. Content can be updated and read back using configure and cget.
```python
import tkinter as tk
from tkinterweb import HtmlLabel
root = tk.Tk()
# Simple styled label
label = HtmlLabel(root, text="Bold and italic text")
label.pack(pady=10)
# Rich label with colours and links
rich = HtmlLabel(root, text="""
★ TkinterWeb ★ HTML rendering in Tkinter
""")
rich.pack()
# Update content
label.configure(text="Updated content")
# Read back text
print(label.cget("text"))
root.mainloop()
```
--------------------------------
### TkinterWeb Configuration Options
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/upgrading.rst
Configuration options that can be set to customize TkinterWeb's behavior.
```APIDOC
## TkinterWeb Configuration Options
### tkinterweb-full-page
Attribute to make elements the same height as the viewport. Has no effect when shrink is enabled.
### on_element_script
Callback to run when a JavaScript event attribute on an element is encountered.
### javascript_enabled
Enable or disable JavaScript support.
### tkhtml_version
Choose a specific Tkhtml version to load.
### ssl_cafile
Provide a path to a CA Certificate file for SSL connections.
### request_timeout
Specify the number of seconds to wait before a request times out.
### caret_browsing_enabled
Enable or disable caret browsing mode.
### allowstyling
Set to `"deep"` on elements with embedded widgets to also style their subwidgets.
### request_func
Set a custom script to use to download resources.
```
--------------------------------
### HtmlFrame Text Selection API
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Provides programmatic control over text selection within the HtmlFrame. Users can get the currently selected text, set a specific selection range, select all text, or clear any existing selection. The `get_selection_position` method can also return detailed information about the selection boundaries.
```APIDOC
## HtmlFrame — text selection API
Get, set, and clear the user's text selection programmatically.
```python
import tkinter as tk
from tkinterweb import HtmlFrame
root = tk.Tk()
frame = HtmlFrame(root, selection_enabled=True)
frame.pack(fill="both", expand=True)
frame.load_html("
Select some of this interesting text here.
")
def on_button():
# Get selected string
text = frame.get_selection()
print("Selected:", text)
# Get selection with element + index info
result = frame.get_selection_position(return_elements=True)
if result:
(start_el, start_text, start_idx), (end_el, end_text, end_idx), middle = result
print(f"Start at index {start_idx} in '{start_text}'")
# Programmatically select characters 0–9 of the page text
frame.set_selection_position(start_index=0, end_index=9)
# Select all
frame.select_all()
# Clear
frame.clear_selection()
tk.Button(root, text="Selection info", command=on_button).pack()
root.mainloop()
```
```
--------------------------------
### Configure HtmlFrame at Runtime
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Modify HtmlFrame widget options after creation using configure() or direct key access. Reload or stop rendering as needed.
```python
import tkinter as tk
from tkinterweb import HtmlFrame
root = tk.Tk()
frame = HtmlFrame(root)
frame.pack(fill="both", expand=True)
frame.load_url("https://example.com")
# Change options at runtime
frame.configure(zoom=1.5)
frame.configure(fontscale=1.2)
frame.configure(dark_theme_enabled=True)
frame.configure(images_enabled=False)
frame.configure(
find_match_highlight_color="#f1a1f7",
find_match_text_color="#000",
find_current_highlight_color="#8bf0b3",
selected_text_highlight_color="#9bc6fa",
)
frame.configure(headers={"User-Agent": "MyApp/1.0"})
frame.configure(request_timeout=30)
frame.configure(insecure_https=True) # ignore certificate errors
# Read a value
zoom = frame.cget("zoom") # or frame["zoom"]
print(zoom)
# Reload and stop
frame.reload()
frame.stop()
root.mainloop()
```
--------------------------------
### Create and Append HTML Element
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/dom.rst
Use this to create a new HTML element, set its text content and style, and append it to an existing element within the document.
```python
yourhtmlframe = tkinterweb.HtmlFrame(root, messages_enabled=True)
yourhtmlframe.load_html("
Test
")
container = yourhtmlframe.document.getElementById("container")
new_header = yourhtmlframe.document.createElement("h1")
new_header.textContent = "Hello, world!"
new_header.style.color = "blue"
container.appendChild(new_header)
```
--------------------------------
### Use Notebook Widget for HtmlFrame Tabs
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Provides a custom `Notebook` widget that replaces `ttk.Notebook` for correct tab management with `HtmlFrame` widgets. It supports adding, inserting, selecting, querying, and removing tabs, as well as binding to tab-change events.
```python
import tkinter as tk
from tkinterweb import HtmlFrame, Notebook
root = tk.Tk()
root.geometry("800x600")
notebook = Notebook(root)
notebook.pack(fill="both", expand=True)
notebook.enable_traversal()
# Create tab pages
page1 = HtmlFrame(notebook)
page1.load_html("
")
# Add tabs
notebook.add(page1, text="Home")
notebook.add(page2, text="Web")
notebook.insert(1, page3, text="Inserted") # insert at position 1
# Select a tab
notebook.select(page2)
active = notebook.select() # returns selected widget
# Query / modify tab options
notebook.tab(page1, text="New Title")
# Iterate tabs
for widget in notebook.tabs():
print(widget)
# Remove a tab
notebook.forget(page3)
# Tab-change event
notebook.bind("<>", lambda e: print("Tab changed"))
root.mainloop()
```
--------------------------------
### Bind Right-Click Event to Show Context Menu
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/usage.rst
Handle right-click events on the HtmlFrame to display a context menu with options to open links.
```python
def on_right_click(event):
# Get the element under the mouse and its url
element = yourhtmlframe.get_currently_hovered_element()
url = element.getAttribute("href")
if url:
# Resolve the url to ensure it is a full url
url = yourhtmlframe.resolve_url(url)
# Create the menu and add a button with the url
menu = tk.Menu(root, tearoff=0)
menu.add_command(label="Open %s" % url,
command=lambda url=url: yourhtmlframe.load_url(url))
# Show the menu
menu.tk_popup(event.x_root, event.y_root, 0)
yourhtmlframe.bind("", on_right_click)
```
--------------------------------
### JSEngine Class Methods
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/api/jsengine.rst
The JSEngine class provides methods to interact with the JavaScript engine. The members listed are directly callable by users.
```APIDOC
## JSEngine Class
This class provides methods to interact with the JavaScript engine.
### Methods
(Members of this class are documented here, but specific method signatures and details are not provided in the source text.)
```
--------------------------------
### Evaluate JavaScript and Register Python Objects
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Demonstrates how to enable JavaScript execution within an HtmlFrame and register Python functions or objects as global JavaScript variables. Requires `javascript_enabled=True` and a specified backend. The 'python' backend allows Python code to be executed via the JS interface.
```python
import tkinter as tk
from tkinterweb import HtmlFrame
root = tk.Tk()
# Use javascript_backend="python" to run Python code via the JS interface
frame = HtmlFrame(root, javascript_enabled=True, javascript_backend="python")
frame.pack(fill="both", expand=True)
frame.load_html("""
0
""")
count = [0]
def increment():
count[0] += 1
frame.document.getElementById("counter").textContent = str(count[0])
# Register Python callables / objects as JS globals
frame.javascript.register("increment", increment)
frame.javascript.register("document", frame.document)
# Evaluate JS (or Python when backend="python")
frame.javascript.eval("document.getElementById('counter').textContent = '99'")
# PythonMonkey backend example
# frame2 = HtmlFrame(root, javascript_enabled=True, javascript_backend="pythonmonkey")
# frame2.javascript.register("alert", lambda msg: print("ALERT:", msg))
# frame2.javascript.eval("alert('hello from JS')")
root.mainloop()
```
--------------------------------
### Complete Mini-Browser with TkinterWeb
Source: https://context7.com/andereoo/tkinterweb/llms.txt
This code implements a functional mini-browser using TkinterWeb. It sets up a tabbed interface with navigation controls, handles URL changes, title updates, and resource loading events. It also demonstrates basic DOM manipulation by finding all links on a loaded page.
```python
import tkinter as tk
from tkinterweb import HtmlFrame, Notebook
from tkinterweb.utilities import (
DONE_LOADING_EVENT, URL_CHANGED_EVENT, TITLE_CHANGED_EVENT,
DOWNLOADING_RESOURCE_EVENT,
)
root = tk.Tk()
root.title("Mini Browser")
root.geometry("900x600")
notebook = Notebook(root)
notebook.pack(fill="both", expand=True)
def new_tab(url="about:tkinterweb"):
page_frame = tk.Frame(notebook)
# Top bar
bar = tk.Frame(page_frame)
bar.pack(fill="x")
back_btn = tk.Button(bar, text="◀")
stop_btn = tk.Button(bar, text="■")
url_entry = tk.Entry(bar)
go_btn = tk.Button(bar, text="Go")
back_btn.pack(side="left")
stop_btn.pack(side="left")
url_entry.pack(side="left", fill="x", expand=True)
go_btn.pack(side="left")
html = HtmlFrame(
page_frame,
messages_enabled=False,
on_navigate_fail=lambda u, e, c: html.load_html(f"
Error {c}
{e}
"),
)
html.pack(fill="both", expand=True)
def navigate(event=None):
url_val = url_entry.get()
if not url_val.startswith(("http", "file", "about")):
url_val = "http://" + url_val
html.load_url(url_val)
def on_url_change(event):
url_entry.delete(0, "end")
url_entry.insert(0, html.current_url)
notebook.tab(page_frame, text=html.current_url[:25])
def on_title_change(event):
root.title(html.title)
notebook.tab(page_frame, text=(html.title or html.current_url)[:25])
def on_downloading(event):
stop_btn.config(command=html.stop)
def on_done(event):
stop_btn.config(command=lambda: None)
# DOM manipulation after load
links = html.document.querySelectorAll("a[href]")
print(f"{len(links)} links found on page")
html.bind(URL_CHANGED_EVENT, on_url_change)
html.bind(TITLE_CHANGED_EVENT, on_title_change)
html.bind(DOWNLOADING_RESOURCE_EVENT, on_downloading)
html.bind(DONE_LOADING_EVENT, on_done)
url_entry.bind("", navigate)
go_btn.config(command=navigate)
notebook.add(page_frame, text="New tab")
notebook.select(page_frame)
html.load_url(url)
new_tab("about:tkinterweb")
root.mainloop()
```
--------------------------------
### Initialize TkinterWeb HtmlText Widget
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/caret.rst
Instantiate the HtmlText widget for creating editable HTML content. Ensure messages are enabled for feedback.
```python
from tkinterweb import HtmlText
yourhtmlframe = HtmlText(root, messages_enabled=True)
```
--------------------------------
### Generate Style Report and Debug with HtmlFrame
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Demonstrates generating an interactive style report to inspect computed CSS for elements and finding the HTMLElement wrapping a Tkinter widget using HtmlFrame. The style report can be displayed or returned as HTML.
```python
import tkinter as tk
from tkinterweb import HtmlFrame
root = tk.Tk()
frame = HtmlFrame(root, messages_enabled=True,
message_func=lambda msg: print("[TkinterWeb]", msg))
frame.pack(fill="both", expand=True)
frame.load_html("
Styled heading
")
# Open the interactive style report in a new window
frame.generate_style_report(return_report=False)
# Or retrieve the raw HTML report string
report_html = frame.generate_style_report(return_report=True)
print(report_html[:300])
# widget_to_element: find the HTMLElement wrapping a Tkinter widget
btn = tk.Button(frame, text="Find me")
frame.add_html(f'')
el = frame.widget_to_element(btn)
print(el.tagName) # object
root.mainloop()
```
--------------------------------
### Caret Browsing API for HtmlFrame
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Enable caret browsing for editable or navigable content within the HtmlFrame. Requires `caret_browsing_enabled=True` during initialization. Allows programmatic control of the caret's position.
```python
import tkinter as tk
from tkinterweb import HtmlFrame
root = tk.Tk()
frame = HtmlFrame(root, caret_browsing_enabled=True)
frame.pack(fill="both", expand=True)
frame.load_html("
Move the caret through this text.
")
def show_caret():
result = frame.get_caret_position(return_element=True)
if result:
element, text, index = result
print(f"Caret at index {index} in '{text}'")
# Move the caret to character index 5 of the page text
frame.set_caret_position(index=5)
# Shift left / right
frame.shift_caret_left()
frame.shift_caret_right()
tk.Button(root, text="Show caret", command=show_caret).pack()
root.mainloop()
```
--------------------------------
### Tkinterweb Editor Basic Operations
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Demonstrates basic text manipulation and event binding for the Tkinterweb editor. Use for text insertion, deletion, and reacting to changes.
```python
editor.delete(0, 8)
# Insert at caret position
editor.insert("insert", " [caret text]")
# Insert an HTMLElement
new_elem = editor.document.createElement("b")
new_elem.textContent = "Bold"
editor.insert("end", new_elem)
# React to changes
editor.bind(FIELD_CHANGED_EVENT, lambda e: print("Changed:", editor.get_page_text()))
# Disable editing
editor.configure(state="disabled")
root.mainloop()
```
--------------------------------
### Enable Dark Theme in HtmlFrame
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/usage.rst
Activate dark mode for the HtmlFrame by setting dark_theme_enabled to True. Optionally, enable image inversion to adjust images for a darker theme.
```python
yourhtmlframe.configure(dark_theme_enabled=True)
```
--------------------------------
### HtmlFrame.load_html
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Loads an HTML string directly into the HtmlFrame without requiring a network request. This is useful for dynamic content, templates, and offline rendering. The `base_url` parameter is used to resolve relative paths for resources like images and CSS, and the `fragment` parameter can be used to jump to a specific section of the HTML.
```APIDOC
## HtmlFrame.load_html — render HTML string
Load an HTML string directly without a network request. Useful for dynamic content, templates, and offline rendering.
```python
import tkinter as tk
from tkinterweb import HtmlFrame
root = tk.Tk()
frame = HtmlFrame(root)
frame.pack(fill="both", expand=True)
html = """
Dashboard
Status: Running
Version: 4.25.2
"""
# base_url is used to resolve relative paths (images, CSS)
frame.load_html(html, base_url="file:///my/app/", fragment="section1")
root.mainloop()
```
```
--------------------------------
### Configure TkinterWeb Callback Hooks
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Use these callbacks to customize how TkinterWeb handles navigation failures, link clicks, form submissions, and script tags. They are passed at construction time or via `configure()`.
```python
import tkinter as tk
from tkinterweb import HtmlFrame
root = tk.Tk()
def handle_error(url, error, code):
"""Called when a URL fails to load."""
print(f"[{code}] Could not load {url}: {error}")
def handle_link(url):
"""Called when a hyperlink is clicked. Default: frame.load_url(url)"""
if "external.com" in url:
import webbrowser
webbrowser.open(url)
else:
frame.load_url(url)
def handle_submit(url, data, method):
"""Called when a form is submitted. Default: frame.load_form_data(...) """
print(f"Form submit {method} -> {url}: {data}")
frame.load_form_data(url, data, method)
def handle_script(attributes, contents):
"""Called when a
Test
")
```
--------------------------------
### TkinterWeb Notebook Widget
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/api/notebook.rst
The TkinterWeb Notebook widget is a drop-in replacement for ttk.Notebook, offering improved compatibility and stability.
```APIDOC
## tkinterweb.Notebook
### Description
This widget should be used in place of `ttk.Notebook` due to compatibility issues with Tkhtml on 64-bit Windows.
### Events
This widget emits the following Tkinter virtual events:
* `<>`: Generated whenever the selected tab changes.
### See Also
- `ttk.Notebook` API: https://docs.python.org/3/library/tkinter.ttk.html#notebook
```
--------------------------------
### Bind to UrlChanged Event to Handle URL Updates
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/usage.rst
Bind to the '<>' event to detect and handle changes in the current URL, such as after redirects.
```python
def url_changed(event):
updated_url = yourhtmlframe.current_url
### Do stuff, such as change the content of an address bar
yourhtmlframe.bind("<>", url_changed)
```
--------------------------------
### Headless HTML Parsing with HtmlParse
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Parse HTML content without a visible window using HtmlParse. Access the full DOM API to query and extract information from the loaded HTML.
```python
from tkinterweb import HtmlParse
parser = HtmlParse()
parser.load_html("""
Hello
Apple
Banana
""")
# Use the DOM API
title = parser.document.getElementById("title")
print(title.textContent) # Hello
items = parser.document.getElementsByClassName("item")
for item in items:
print(item.innerText) # Apple / Banana
# Get serialised HTML
print(str(parser)) # ...
parser.destroy()
```
--------------------------------
### Handle Keypresses for Text Insertion
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/caret.rst
Implement a keypress handler to insert characters into the document at the caret's position. This custom binding overrides default behavior.
```python
def on_keypress(event):
# Get the caret's position
caret_position = yourhtmlframe.get_caret_position()
if caret_position and event.char:
element, text, index = caret_position
# Add the key's character to the element's text
newtext = text[:index] + event.char + text[index:]
# Set the element's text
element.textContent = newtext
# Shift the caret right
yourhtmlframe.shift_caret_right()
yourhtmlframe.bind("", on_keypress)
```
--------------------------------
### Append HTML and Inject CSS with HtmlFrame
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Incrementally add HTML content to the current document or inject CSS without a full page reload. CSS can be injected with different priorities ('agent', 'user', 'author').
```python
import tkinter as tk
from tkinterweb import HtmlFrame
root = tk.Tk()
frame = HtmlFrame(root)
frame.pack(fill="both", expand=True)
frame.load_html("
")
# Append HTML at the end of the document
frame.add_html("
Item 1
")
frame.add_html("
Item 2
")
# Insert at a specific position (index 0 = before first child of )
element = frame.add_html("
Item 0
", return_element=True, index=0)
print(element.tagName) # -> li
# Inject CSS with different priorities: "agent" < "user" < "author" (default)
frame.add_css("body { background-color: #1e1e1e; color: #d4d4d4; }", "author")
frame.add_css("li { list-style-type: disc; margin: 4px; }", "user")
# Import a CSS file by URL
frame.import_css("https://example.com/styles.css")
root.mainloop()
```
--------------------------------
### TkinterWeb Classes
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/upgrading.rst
Key classes introduced in various versions of TkinterWeb.
```APIDOC
## TkinterWeb Classes
### HtmlParse
Represents the HTML parsing functionality.
### TkHtmlParsedURI
Represents a parsed URI within Tkhtml.
### HTMLCollection
Represents a collection of HTML elements.
### CaretManager
Manages caret behavior and position.
### EventManager
Manages event handling and dispatching.
### HtmlText
Represents text content within an HTML context.
### SelectionManager
Manages text selection within the widget.
### WidgetManager
Manages Tkinter widgets embedded within HTML.
### JSEngine
Represents the JavaScript execution engine.
```
--------------------------------
### HTMLElement Methods
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/api/htmldocument.rst
Methods related to HTML elements within the document.
```APIDOC
## HTMLElement
Represents an HTML element within the document. Methods are inherited or defined within this class.
### Methods
(Members are documented via autoclass directive in the source, specific methods are not listed here.)
```
--------------------------------
### Htmlframe Method Updates (Version 4.12)
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/upgrading.rst
In version 4.12, the `register_JS_object` method on `Htmlframe` was updated to use the `register` method in `JSEngine`.
```APIDOC
## Htmlframe Method Updates
### Description
The `register_JS_object` method on `Htmlframe` has been updated.
### Method
- `Htmlframe.register_JS_object()` - Use `JSEngine.register()`
```
--------------------------------
### Load HTML String with HtmlFrame
Source: https://context7.com/andereoo/tkinterweb/llms.txt
Load an HTML string directly into the HtmlFrame. The `base_url` parameter is crucial for resolving relative paths for resources like images and CSS.
```python
import tkinter as tk
from tkinterweb import HtmlFrame
root = tk.Tk()
frame = HtmlFrame(root)
frame.pack(fill="both", expand=True)
html = """
Dashboard
Status: Running
Version: 4.25.2
"""
# base_url is used to resolve relative paths (images, CSS)
frame.load_html(html, base_url="file:///my/app/", fragment="section1")
root.mainloop()
```
--------------------------------
### HtmlFrame Methods
Source: https://github.com/andereoo/tkinterweb/blob/main/docs/source/upgrading.rst
Methods available on the HtmlFrame class for interacting with HTML content and page elements.
```APIDOC
## HtmlFrame Methods
### register_JS_object
Register a JavaScript object with the TkinterWeb instance.
### widget_to_element
Convert a Tkinter widget to an HTML element representation.
### insert_html
Insert HTML content into the current document.
### get_page_text
Retrieve the entire text content of the current page.
### get_caret_position
Get the current caret position within the page.
### get_caret_page_position
Get the current caret position relative to the page.
### set_caret_position
Set the caret position within the page.
### set_caret_page_position
Set the caret position relative to the page.
### shift_caret_left
Move the caret one position to the left.
### shift_caret_right
Move the caret one position to the right.
### get_selection_position
Get the current selection position within the page.
### get_selection_page_position
Get the current selection position relative to the page.
### set_selection_position
Set the selection position within the page.
### set_selection_page_position
Set the selection position relative to the page.
### unbind
Remove an event binding from an HTML element.
```