Shortcuts#
Register named keyboard shortcuts with platform-agnostic patterns, bind them to
your app, and let menus display the resolved shortcut text. A pattern like
Mod+S becomes Ctrl+S on Windows and Linux and ⌘S on macOS, so you
write the shortcut once and it reads correctly everywhere.
A shortcut has three parts: a key (your own identifier, e.g. "save"), a
pattern (the key combination), and a command (the function to run).
The shortcut service#
get_shortcuts() returns the shared service. Register your shortcuts, then
call bind_to(app) once to make them live. register() returns the created
Shortcut, and raises ValueError if
the key is already taken — so each key is registered exactly once:
from bootstack.shortcuts import get_shortcuts
import bootstack as bs
with bs.App(title="Editor") as app:
shortcuts = get_shortcuts()
shortcuts.register("save", "Mod+S", save_file)
shortcuts.register("find", "Mod+F", open_search)
shortcuts.register("quit", "Mod+Q", app.quit)
shortcuts.bind_to(app) # activate the bindings on the app window
app.run()
Shortcuts registered after bind_to are bound to that window automatically,
so you can register more as your app grows without binding again.
Patterns#
A pattern is modifier names joined to a key with +. Use Mod for the
primary modifier and the framework picks the right one per platform:
Mod— the primary modifier:Ctrlon Windows/Linux,Commandon macOS.Shift,Alt(Optionon macOS),Ctrl.Function keys (
F1–F12) and ordinary letters/digits, with or without modifiers.
shortcuts.register("new", "Mod+N", new_doc)
shortcuts.register("new_window", "Mod+Shift+N", new_window)
shortcuts.register("refresh", "F5", reload_data)
shortcuts.register("close", "Alt+F4", close_window)
Inspecting and removing shortcuts#
Look a shortcut up by key, enumerate everything registered, or remove one. A
Shortcut exposes its key,
pattern, command, and the read-only display label:
sc = shortcuts.get("save") # the Shortcut, or None if unregistered
sc.pattern # "Mod+S"
sc.display # "Ctrl+S" / "⌘S"
for key, sc in shortcuts.all().items():
print(key, "→", sc.display)
shortcuts.unregister("find") # remove one (KeyError if not registered)
shortcuts.unbind_from(app) # detach every binding from a window
See also#
MenuButton — menus that display registered shortcuts.
API reference#
The complete reference — the Shortcuts
service, get_shortcuts(), and the Shortcut record — lives in Shortcuts.
At a glance:
Get the global Shortcuts service instance. |
|
Singleton service for managing keyboard shortcuts. |
|
A registered keyboard shortcut. |