Embedding Widgets
Note
The API changed significantly in version 4. See the changelog for details.
Overview
By default, Tkinter provides three geometry managers: pack, place, and grid. While these geometry managers are very powerful, achieving certain layouts, especially with scrolling, can be very difficult.
TkinterWeb provides a system for attaching Tkinter widgets onto the window, and handles layouts, images, selection, scrolling, and much more for you.
How-to
To place a Tkinter widget inside an HTML document, add the data=[yourwidget] attribute to an <object> element. For example, to add a button under some italic text, one could do:
yourframe = tkinterweb.HtmlFrame(root, messages_enabled=True)
yourbutton = tkinter.Button(yourframe, text="Hello, world!")
source_html = f"<i>This is some text</i><br><object data={yourbutton}></object>"
yourframe.load_html(source_html) # or use add_html to add onto the existing document
Ensure your HtmlFrame widget was created before the widget you are embedding, or else the widget might not be visible.
Tip
Add the allowstyling attribute to automatically change the widget’s background color, text color, and font to match the containing HTML element. Use allowstyling="deep" to also style subwidgets (new in version 4.9).
Add the handledelete attribute to automatically call destroy() on the widget when it is removed from the page (i.e. if another webpage is loaded).
Note
By default, scrolling over an embedded widget will scroll the page if the widget or subwidgets do not handle scrolling themselves (new in version 4.9). You can override this behaviour by adding the allowscrolling or allowscrolling=false attribute.
Widget position and sizing can be modified using CSS styling on the widget’s associated <object> element.
See Manipulating the Page (new in version 3.25) for more details.
To get the element containing your widget, either use HtmlFrame.widget_to_element().
Widget handling
You can also set, remove, or change the widget in any element later (new in version 4.2):
yourbutton = tkinter.Button(yourframe, text="Hello, world!")
...
yourelement = yourframe.document.getElementById("#container") # get the element to fill
yourelement.widget = yourbutton # set the element's widget
The widget can be removed from the element via yourelement.widget = None.
Please report bugs or request new features on the issues page.