bootstack.AppShell#
- class bootstack.AppShell(*, title='', size=None, theme=None, icon=None, light_theme='bootstrap-light', dark_theme='bootstrap-dark', follow_system_appearance=False, available_themes=(), locale=None, localize_mode='auto', window_style='mica', macos_quit_behavior='native', remember_window_state=False, state_path=None, on_close=None, position=None, min_size=None, max_size=None, resizable=None, scaling=None, hdpi=True, sidebar_surface='raised', statusbar_surface='chrome', undecorated=False, show_sidebar=True, sidebar_mode='expanded', sidebar_width=None, collapsible=True, nav_accent='primary', remember_nav_state=False, show_statusbar=False, **kwargs)#
Bases:
_SidebarHost,_ShellBaseSingle-tier application window: one navigation sidebar plus content.
The everyday desktop scaffold — an optional toolbar stack across the top, one navigation sidebar on the left, a content area that swaps as you navigate, and an optional status band along the bottom. For a multi-section app with a workspace rail, use
Workbenchinstead.Declare the sidebar with exactly one provider front door:
page_nav()(authored pages),list_nav()/tree_nav()(data-bound master-detail), orcustom_nav()(hand-built). Pages support context-manager syntax so widgets inside thewithblock are parented automatically.Like
App, configuration is a single flat path: pass options as constructor kwargs and read or change them through matchingshell.*properties (e.g.shell.theme,shell.locale,shell.sidebar_mode).- Parameters:
title (str) – Window title and (in undecorated mode) chrome label.
size (tuple[int, int] | None) – Initial window size as
(width, height).theme (str | None) – Theme name to apply on startup (e.g.
'bootstrap-dark').icon (str | Image | AppIcon | None) – Title-bar and taskbar icon — an icon file path, an
Imagehandle, or anAppIcon. Defaults to the bootstack icon.light_theme (str) – Theme used for the light end of system-appearance tracking and
toggle_theme.dark_theme (str) – Theme used for the dark end of system-appearance tracking and
toggle_theme.follow_system_appearance (bool) – If True, switch between
light_themeanddark_themeto match the OS (currently effective on macOS).available_themes (Sequence[str]) – Theme names to expose to theme pickers.
locale (str | None) – Locale identifier (e.g.
'en_US','de_DE').localize_mode (LocalizeMode) – Localization behavior.
window_style (WindowStyle | str | None) – Windows-only window effect, or None to disable.
macos_quit_behavior (Literal['native', 'classic']) – macOS close / Cmd+Q behavior. No-op on Win/Linux.
remember_window_state (bool) – If True, window geometry is saved and restored.
state_path (str | None) – Optional override for the persisted window-state file.
on_close (Callable[[], bool | None] | None) – Handler invoked when the user clicks the window’s close button. Return
Falseto veto the close;NoneorTrueto allow it.position (tuple[int, int] | None) – Initial window position as
(x, y).min_size (tuple[int, int] | None) – Minimum window size as
(width, height).max_size (tuple[int, int] | None) – Maximum window size as
(width, height).resizable (tuple[bool, bool] | None) – Whether the window can be resized as
(x, y).scaling (float | None) – Explicit UI scaling factor. When None, scaling is automatic.
hdpi (bool) – Enable high-DPI awareness for the application. Default
True.sidebar_surface (SurfaceToken | str) – Surface token for the navigation sidebar.
statusbar_surface (SurfaceToken | str) – Surface token for the bottom status band.
undecorated (bool) – Remove OS window decorations and draw a custom border. Ignored on macOS. The shell gets a built-in draggable title bar with min/max/close; add your own with
add_toolbar(show_window_controls=True)to take over the chrome.show_sidebar (bool) – Render the sidebar region. Default
True.sidebar_mode (SidebarMode) – Initial sidebar mode —
'expanded'/'compact'/'hidden'.'compact'(icon-only) applies to an authoredpage_navsidebar.sidebar_width (int | None) – Expanded sidebar width in pixels.
collapsible (bool) – Allow collapsing the sidebar; binds Ctrl/Cmd-B. Default
True.nav_accent (AccentToken | str | None) – Accent for the active nav item. Defaults to
'primary'; set another accent token to retint, orNonefor a neutral wash.remember_nav_state (bool) – Persist the sidebar mode and active page across sessions. Default
False.show_statusbar (bool) – Force the bottom status band on (otherwise it appears once a status segment is added). Default
False.
- property content: Page#
The content region as a container for hand-driven content.
Use with
with host.content:orparent=host.contentto place widgets in the content area directly — the escape hatch forcustom_navmode.
- property follow_system_appearance: bool#
Whether the app tracks the OS light/dark appearance (macOS).
- property locale_date_format: str | None#
Short date pattern for the active locale (e.g.
'M/d/yy'). Read-only.
- property locale_language: str | None#
Base language code derived from the locale (e.g.
'en'). Read-only.
- property locale_thousands: str | None#
Thousands separator for the active locale (e.g.
','). Read-only.
- property locale_time_format: str | None#
mm a. Read-only.
- Type:
Short time pattern for the active locale, e.g. h
The active provider’s sidebar navigation panel (or
None).
- property remember_window_state: bool#
Whether window geometry is saved on close and restored on launch.
- property schedule: Schedule#
Scheduler tied to this widget’s lifetime.
All jobs are automatically cancelled when the widget is destroyed. First access creates the
Scheduleinstance; subsequent accesses return the same instance.Usage:
self.schedule.delay(500, callback) self.schedule.every(1000, tick) job = self.schedule.idle(refresh) job.cancel()
- property sidebar_mode: Literal['expanded', 'compact', 'hidden']#
The sidebar mode (
'hidden'/'compact'/'expanded').
- property statusbar: StatusBar#
The bottom status band (passive status). Lazily created on first access.
The band renders once a segment is added (or
show_statusbar=True).
- property window_style: WindowStyle | str | None#
Windows-only window effect, or None to disable.
- classmethod from_store(store, **overrides)#
Construct from a persisted
Store(or plain dict).Reads configuration from
store, tolerantly ignoring keys that are not valid configuration (so version skew does not raise). Explicit keywordoverrideswin over stored values. SeeApp.from_store.
- add_close_handler(handler)#
Register a veto-able close handler — an alias for
on_close().
- add_toolbar(*, divider=False, use_macos_menus=True, **toolbar_kwargs)#
Append a
Toolbarto the window’s top chrome stack and return it.Toolbars stack full-width, top-to-bottom, in the order added — fill each with buttons, labels, widgets, and menus (
toolbar.add_menu(...)). The returnedToolbaris a context manager, so the natural form reads:with window.add_toolbar() as tb: tb.add_menu("File") tb.add_spacer() tb.add_theme_toggle()
- Parameters:
divider (bool) – Draw a hairline beneath this toolbar (default
False).use_macos_menus (bool) – On macOS, bridge this toolbar’s menus to the native global menu bar (in-window dropdowns hide). Default
True; setFalseto keep its menus in-window even on macOS. No effect on Windows/Linux.**toolbar_kwargs (Any) – Forwarded to
Toolbar— e.g.surface,density,button_variant,show_window_controls,draggable. Window chrome defaultssurface='chrome'anddensity='compact'(a tight strip); passdensity='default'for a roomier bar.
- Returns:
The
Toolbarfor this layer.- Return type:
- capture(path, *, inset=0, settle=0.1)#
Save a picture of this widget to an image file.
Captures the area this widget occupies on screen — one widget, a whole window, or the entire application, depending on what you call it on. The file extension selects the format, so
.png,.jpg, and.pdfall work.The widget has to be visible. A capture reads pixels from the display, so the window is brought to the front first and a hidden or detached widget cannot be captured at all. Any always-on-top setting the window already had is left as it was found.
Pair it with a save dialog to let the user choose where it goes:
import bootstack as bs def on_export(): chosen = bs.ask_save_file(initial_file="dashboard.png") if chosen: app.capture(chosen)
- Parameters:
path (str | Path) – Where to write the image. Missing parent folders are created, and the extension chooses the format.
inset (int) – Pixels to trim from every edge, zero or more. Use
2on a whole window to drop the native border artifact.settle (float) – Seconds to let the desktop finish repainting before the pixels are read. The default covers the common case of a dialog closing just beforehand. The interface pauses for this long, so a second click on the control that started the capture waits its turn rather than starting an overlapping one.
- Returns:
The path that was written.
- Raises:
BootstackError – If the widget is not visible on screen or has been scrolled out of view, if
insetis negative, if no capture backend is available, or if the file cannot be written.- Return type:
Path
Added in version 0.3.0.
- close()#
Close the window and exit its event loop.
For the application window this quits the loop started by
run()— the natural action for a “Quit” command. It does not run theon_closeveto handlers (those guard the user clicking the window’s close button), so a programmaticclose()always proceeds.
Declare a hand-built sidebar; return its container.
The escape hatch when none of the providers fit — fill the returned container with your own sidebar UI (e.g. a
bs.Accordion) and drive the content region yourself viacontent.
- destroy()#
Destroy the widget and release the resources it holds.
Removes the widget from its parent, destroys its children, and cancels any pending or repeating jobs on its
schedule. After this the widget must not be used again. Destroying a container destroys everything inside it.
- detail(fn)#
Register the detail-body renderer for a data-bound sidebar (decorator).
Pairs with
list_nav/tree_navto form a master-detail view: when the selection changes,fnruns with the selected record and rebuilds the content area. The first row is selected on load, so the detail is never empty on open.
- emit(event, *, data=None)#
Fire a named event on this widget, as if it produced the event itself.
This is how a composite widget surfaces high-level activity to its listeners, and the generic counterpart to the
on_*()shorthands for firing events that have no dedicated method.It is meant for the framework’s own events —
'change','select','input'and the rest of the data-carrying names. A handler registered throughon()or anon_<event>()shorthand receives what is emitted.Names that map onto a native event instead (
'click','focus','blur','submit', …) are a different matter: emitting one asks the toolkit to deliver a real input event, which carries no payload and can reach handlers the widget installed for its own use. Emitting those is not a way to notify listeners, and a listener bound throughon()may not see it. Drive the widget through its properties and methods instead.- Parameters:
Example
from bootstack.events import ChangeEvent field.emit("change", data=ChangeEvent(value=new_value))
- hide()#
Hide the window without destroying it.
The window is unmapped (and usually removed from the taskbar). Bring it back with
show().
- hide_sidebar()#
Hide the sidebar entirely.
Declare a data-bound list sidebar from a
DataSource(flat master-detail).Records render their
icon/title/textin a recycling list. Pair it with@detailto render the body for the selected record. Returns theListViewdriving the sidebar — use it to read.selectionor drive selection (select_items).- Parameters:
source (Any) – A
DataSource(orrows=-compatible record list).separator (bool) – Draw divider lines between rows. Default
False(flush).density (WidgetDensity) –
'default'(richer two-line rows) or'compact'(one-line).placeholder (str) – Empty-state message shown when the source has no records.
chevron (bool) – Add a per-row disclosure chevron. Default
False.
- maximize()#
Maximize the window where the platform supports it.
- minimize()#
Minimize the window to the taskbar or dock.
Navigate to a page; the sidebar selection follows.
- on(event, handler=None)#
Bind
handlertoevent, or return a composableStream.With a handler — binds immediately and returns a
Subscription:sub = widget.on("change", handler) sub.cancel()
Without a handler — returns a
Streamfor operator chaining. The Tk binding is created lazily when.listen()is called:sub = widget.on("change").debounce(300).listen(handler) sub.cancel()
- Parameters:
event (str) – Event name (e.g.
"change","click").handler (Callable[[Any], Any] | None) – Optional callback. If omitted, a
Streamis returned.
- Returns:
Subscriptionwhen a handler is provided;Streamotherwise.- Return type:
- on_close(handler)#
Register a handler invoked when the user clicks the window’s close button.
Handlers run in registration order; return
Falsefrom one to veto the close (the window stays open), orNone/Trueto allow it. This guards the close-button gesture only — it is not run by the programmaticclose().
- on_destroy(handler=None)#
Register a callback fired when the widget is destroyed.
Fires once, as the widget is torn down — the place to release resources the widget owns that aren’t cleaned up automatically (file handles, observers, external subscriptions). The handler receives a curated
Event.- Parameters:
handler (Callable[[Event], Any] | None) – Called as the widget is destroyed. Omit to get a composable
Stream.- Returns:
A cancellable
Subscriptionwhen a handler is given, otherwise aStream.- Return type:
- on_locale_change(handler=None)#
React to locale changes; the handler receives the new locale code.
- Returns:
Subscription(with handler) orStream(without handler).- Return type:
- on_page_change(handler=None)#
Register a callback fired when the active page changes.
- Parameters:
handler (Callable[[PageChangeEvent], Any] | None) – Called with a
PageChangeEvent(the new and previous page keys, plus anynavigate()data). Omit to get a composableStream.
- on_sidebar_mode_change(handler=None)#
Register a callback fired when the sidebar mode changes.
- Parameters:
handler (Callable[[DisplayModeEvent], Any] | None) – Called with a
DisplayModeEvent(compact↔expanded). Omit to get a composableStream.
- on_sidebar_toggle(handler=None)#
Register a callback fired when the sidebar is shown or hidden.
- Parameters:
handler (Callable[[PaneToggleEvent], Any] | None) – Called with a
PaneToggleEvent. Omit to get a composableStream.
- on_theme_change(handler=None)#
React to theme changes; the handler receives the new theme name.
Fired after the theme is fully rebuilt, so handlers can safely read new colors. Useful for persisting the choice, e.g.
app.on_theme_change(lambda t: store.update(theme=t)).- Returns:
Subscription(with handler) orStream(without handler).- Return type:
Declare the sidebar as an authored page list; return its handle.
- Parameters:
variant (Literal['ghost', 'solid']) – How an accented selection reads —
'ghost'(default) is a subtle accent wash behind full-strength text;'solid'fills the selected item with the accent and uses on-accent (white) text for higher emphasis. Needsnav_accent; withnav_accent=Noneit falls back to a neutral wash.- Returns:
A
PageNavhandle — author items withadd_page()/add_header()/add_divider()/add_footer_page().- Return type:
- remove_close_handler(handler)#
Remove a close handler previously registered with
on_close().
- run()#
Show the window and start the event loop.
- set_fullscreen(value=True)#
Enter or leave fullscreen mode where supported.
- Parameters:
value (bool) –
Trueto enter fullscreen,Falseto exit. DefaultTrue.
- set_topmost(value=True)#
Pin the window above all others, or release it.
- Parameters:
value (bool) –
Trueto keep the window above others,Falseto release. DefaultTrue.
- show()#
Show the window — typically to reveal it again after
hide().For the application window,
run()already shows it and starts the event loop; reach forshow()to bring a hidden window back.
- show_sidebar()#
Show the sidebar, restoring its last non-hidden mode.
- toggle_sidebar()#
Toggle the sidebar between hidden and shown (the hamburger action).
Declare a data-bound tree sidebar (hierarchical master-detail).
Declare the hierarchy inline with
nodes=or project a flat adjacency-listsource=(each row names its parent viaparent_field). Pair it with@detailto render the body for the selected node. Returns theTreedriving the sidebar — use it to drive the view (expand/expand_all/collapse/select/find).- Parameters:
nodes (list | None) – Inline hierarchy as a node list, or
Noneto usesource.source (Any) – A flat adjacency-list
DataSource, orNoneto usenodes.parent_field (str) – Field naming each row’s parent (for
source).label_field (str) – Field providing each node’s label.
icon_field (str) – Field providing each node’s icon name.
density (WidgetDensity) –
'default'or'compact'.placeholder (str) – Empty-state message shown until a node is picked.
Supporting classes#
Opaque handles returned by AppShell’s methods — you obtain them from the shell
rather than constructing them directly. (The status band is a standalone widget;
see StatusBar.)
Bases:
objectAuthorable page-list sidebar — the handle returned by
page_nav().A page nav is a flat list of authored nav items, each paired with a content page. Author it with
add_page()(andadd_header()/add_divider()to chunk the list,add_footer_page()to pin an item to the bottom). Use it as a context manager for grouping; the items themselves are added via the handle, not parented into it.Add a divider to the list.
Add a plain section-label header that chunks the list (grouped-static).
Add a nav item and its content page; return a context-manager page.
The page IS a layout container — the
layout/padding/gap/horizontal_items/vertical_items/grow_items/columns/rows/auto_flowkwargs configure it directly (same asPageStack.add), so children inside thewithblock need no extraColumn/Gridwrapper.- Parameters:
key (str) – Unique identifier for the nav item and page.
text (str) – Display label in the sidebar.
icon (str | dict | None) – Icon name or icon configuration dict.
scrollable (bool) – If
True, wrap the page in a verticalScrollView.pin_to_footer (bool) – If
True, pin the nav item to the bottom of the sidebar (the non-scrolling footer zone) instead of the scrolling main list — handy for a Settings or Account entry.layout (LayoutKind) – Page layout —
'column'(default),'row', or'grid'.padding (Padding | None) – Space inside the page around its content.
gap (int) – Space between the page’s children in pixels.
horizontal_items (str | None) – Cross/main-axis alignment of children on the x-axis.
vertical_items (str | None) – Cross/main-axis alignment of children on the y-axis.
grow_items (bool) – For
'column'/'row', every child grows to share the axis.columns (int | list[int | str] | None) – Column definitions for
'grid'layout.rows (int | list[int | str] | None) – Row definitions for
'grid'layout.auto_flow (AutoFlow) – Grid auto-flow direction for
'grid'layout.
- class bootstack.widgets.appshell.Page(tk_frame, *, scrollable=False, layout='column', padding=None, gap=0, horizontal_items=None, vertical_items=None, grow_items=False, columns=None, rows=None, auto_flow='row')#
Bases:
objectContext-manager proxy for a content page or custom sidebar container.
A page IS a layout container: it accepts the same layout kwargs as
PageStack.add(layout/padding/gap/horizontal_items/vertical_items/grow_items/columns/rows/auto_flow), so children placed inside it need no extraColumn/Gridwrapper. Widgets created insidewith page:parent here automatically;scrollable=Truewraps the content in a vertical scroll area.The column default stretches children across the width (page content fills the content area), unlike a standalone
Column.- guide_layout(child, **layout_kw)#