App¶
The top-level representation of an application.
Usage¶
The App class is the top level representation of all application activity. It is a
singleton object - any given process can only have a single App. That application may
manage multiple windows, but it will generally have at least one window (called the
main_window
).
The application is started by calling main_loop()
. This will invoke
the startup()
method of the app.
import toga
app = toga.App("Simplest App", "com.example.simplest")
app.main_loop()
You can populate an app’s main window by passing a callable as the startup
argument
to the toga.App
constructor. This startup
method must return the content
that will be added to the main window of the app.
import toga
def create_content(app):
return toga.Box(children=[toga.Label("Hello!")])
app = toga.App("Simple App", "com.example.simple", startup=create_content)
app.main_loop()
This approach to app construction is most useful with simple apps. For most complex
apps, you should subclass toga.App
, and provide an implementation of
startup()
. This implementation must assign a value to
main_window
for the app. The possible values are discussed
below; most apps will assign an instance of
toga.MainWindow
:
import toga
class MyApp(toga.App):
def startup(self):
self.main_window = toga.MainWindow()
self.main_window.content = toga.Box(children=[toga.Label("Hello!")])
self.main_window.show()
if __name__ == '__main__':
app = MyApp("Realistic App", "org.beeware.realistic")
app.main_loop()
Every app must have a formal name (a human readable name), and an app ID (a
machine-readable identifier - usually a reversed domain name). In the examples above,
these are provided as constructor arguments. However, you can also provide these
details, along with many of the other constructor arguments, as packaging metadata in a
format compatible with importlib.metadata
. If you deploy your app with Briefcase, this will be done automatically.
A Toga app will install a number of default commands to reflect core application
functionality (such as the Quit/Exit menu item, and the About menu item). The IDs for
these commands are defined as constants on the Command
class. These
commands are automatically installed before startup()
is invoked. If
you wish to customize the menu items exposed by your app, you can add or remove commands
in your startup()
implementation.
Assigning a main window¶
An app must assign main_window
as part of the startup process. However, the value
that is assigned as the main window will affect the behavior of the app.
Window
¶
Most apps will assign an instance of toga.Window
(or a subclass,
such as toga.MainWindow
) as the main window. This window will control
the life cycle of the app. When the window assigned as the main window is closed, the
app will exit.
If you create an App
by passing a startup
argument to the constructor, a
MainWindow
will be automatically created and assigned to main_window
.
None
¶
If your app doesn’t have a single “main” window, but instead has multiple windows that
are equally important (e.g., a document editor, or a web browser), you can assign a
value of None
to main_window
. The resulting behavior is slightly
different on each platform, reflecting platform differences.
On macOS, the app is allowed to continue running without having any open windows. The app can open and close windows as required; the app will keep running until explicitly exited. If you give the app focus when it has no open windows, a file dialog will be displayed prompting you to select a file to open. If the file is already open, the existing representation for the document will be given focus.
On Linux and Windows, when an app closes the last window it is managing, the app will
automatically exit. Attempting to close the last window will trigger any app-level
on_exit()
handling in addition to any window-specific
on_close()
handling.
Mobile, web and console platforms must define a main window.
BACKGROUND
¶
Assigning a value of toga.App.BACKGROUND
as the main window will allow your app
to persist even if it doesn’t have any open windows. It will also hide any app-level
icon from your taskbar.
Background apps are not supported on mobile, web and console platforms.
Life cycle of an app¶
Regardless of what an application does, every application goes through the same life cycle of starting, running, and shutting down.
Application startup is handled by the startup()
method described above.
startup()
cannot be an asynchronous method, as it runs before the
App’s event loop is started.
All other events in the life cycle of the app can be managed with event handlers.
toga.App
defines the following event handlers:
on_running()
occurs as soon as the app’s event loop has started.on_exit()
occurs when the user tries to exit. The handler for this event must return a Boolean value:True
if the app is allowed to exit;False
otherwise. This allows an app to abort the exit process (for example, to prevent exit if there are unsaved changes).
Event handlers can be defined by subclassing toga.App
and overriding the event
handler method, by assigning a value to the event handler when the app instance is
constructed, or by assigning the event handler attribute on an existing app instance.
When the event handler is set by assigning a value to the event handler, the handler
method must accept an app
argument. This argument is not required when subclassing,
as the app instance can be implied. Regardless of how they are defined, event handlers
can be defined as async
methods.
Managing documents¶
When you create an App instance, you can declare the type of documents that your app is
able to manage by providing a value for document_types
. When an app declares that it
can manage document types, the app will automatically create file management menu items
(such as New, Open and Save), and the app will process command line arguments, creating
a toga.Document
instance for each argument matching a registered document type.
For details on how to define and register document types, refer to the documentation on document handling.
Notes¶
On macOS, menus are tied to the app, not the window; and a menu is mandatory. Therefore, a macOS app will always have a menu with the default menu items, regardless of the window being used as the main window.
Apps executed under Wayland on Linux environment may not show the app’s formal name correctly. Wayland considers many aspects of app operation to be the domain of the windowing environment, not the app; as a result, some API requests will be ignored under a Wayland environment. Correctly displaying the app’s formal name requires the use of a desktop metadata that Wayland can read. Packaging your app with Briefcase is one way to produce this metadata.
Reference¶
- class toga.App(formal_name=None, app_id=None, app_name=None, *, icon=None, author=None, version=None, home_page=None, description=None, startup=None, document_types=None, on_running=None, on_exit=None)¶
Create a new App instance.
Once the app has been created, you should invoke the
main_loop()
method, which will start the event loop of your App.- Parameters:
formal_name (str | None) – The human-readable name of the app. If not provided, the metadata key
Formal-Name
must be present.app_id (str | None) – The unique application identifier. This will usually be a reversed domain name, e.g.
org.beeware.myapp
. If not provided, the metadata keyApp-ID
must be present.app_name (str | None) –
The name of the distribution used to load metadata with
importlib.metadata
. If not provided, the following will be tried in order:If the
__main__
module is contained in a package, that package’s name will be used.If the
app_id
argument was provided, its last segment will be used. For example, anapp_id
ofcom.example.my-app
would yield a distribution name ofmy-app
.As a last resort, the name
toga
.
icon (IconContentT | None) – The
icon
for the app. Defaults totoga.Icon.APP_ICON
.author (str | None) – The person or organization to be credited as the author of the app. If not provided, the metadata key
Author
will be used.version (str | None) – The version number of the app. If not provided, the metadata key
Version
will be used.home_page (str | None) – The URL of a web page for the app. Used in auto-generated help menu items. If not provided, the metadata key
Home-page
will be used.description (str | None) – A brief (one line) description of the app. If not provided, the metadata key
Summary
will be used.startup (AppStartupMethod | None) – A callable to run before starting the app.
on_running (OnRunningHandler | None) – The initial
on_running
handler.on_exit (OnExitHandler | None) – The initial
on_exit
handler.document_types (list[type[Document]] | None) – A list of
Document
classes that this app can manage.
- BACKGROUND: str = 'background app'¶
A constant that can be used as the main window to indicate that an app will run in the background without a main window.
- about()¶
Display the About dialog for the app.
Default implementation shows a platform-appropriate about dialog using app metadata. Override if you want to display a custom About dialog.
- Return type:
None
- add_background_task(handler)¶
DEPRECATED – Use
asyncio.create_task
, or override/assignon_running()
.- Parameters:
handler (BackgroundTask)
- Return type:
None
- app: App | None = None¶
The currently running
App
. Since there can only be one running Toga app in a process, this is available as a class property viatoga.App.app
. If no app has been created yet, this is set toNone
.
- property app_id: str¶
The unique application identifier (read-only). This will usually be a reversed domain name, e.g.
org.beeware.myapp
.
- property app_name: str¶
The name of the distribution used to load metadata with
importlib.metadata
(read-only).
- property author: str | None¶
The person or organization to be credited as the author of the app (read-only).
- beep()¶
Play the default system notification sound.
- Return type:
None
- property commands: CommandSet¶
The commands available in the app.
- property dark_mode: bool | None¶
Whether the user has dark mode enabled in their environment (read-only).
- Returns:
A Boolean describing if the app is in dark mode;
None
if Toga cannot determine if the app is in dark mode.
- async dialog(dialog)¶
Display a dialog to the user in the app context.
- property documents: DocumentSet¶
The list of documents associated with this app.
- enter_presentation_mode(windows)¶
Enter into presentation mode with one or more windows on different screens.
Presentation mode is not the same as “Full Screen” mode; presentation mode is when window borders, other window decorations, app menu and toolbars are no longer visible.
- Parameters:
windows (list[Window] | dict[Screen, Window]) – A list of windows, or a dictionary mapping screens to windows, to go into presentation, in order of allocation to screens. If the number of windows exceeds the number of available displays, those windows will not be visible. The windows must have a content set on them.
- Raises:
ValueError – If the presentation layout supplied is not a list of windows or a dict mapping windows to screens, or if any window does not have content.
- Return type:
None
- exit()¶
Unconditionally exit the application.
This does not invoke the
on_exit
handler; the app will be immediately and unconditionally closed.- Return type:
None
- exit_full_screen()¶
DEPRECATED – Use
App.exit_presentation_mode()
.- Return type:
None
- exit_presentation_mode()¶
Exit presentation mode.
- Return type:
None
- hide_cursor()¶
Hide cursor from view.
- Return type:
None
- property home_page: str | None¶
The URL of a web page for the app (read-only). Used in auto-generated help menu items.
- property icon: Icon¶
The Icon for the app.
Can be specified as any valid
icon content
.
- property is_bundled: bool¶
Has the app been bundled as a standalone binary, or is it running as a Python script?
- property is_full_screen: bool¶
DEPRECATED – Use
App.in_presentation_mode
.
- property loop: AbstractEventLoop¶
The event loop of the app’s main thread (read-only).
- main_loop()¶
Start the application.
On desktop platforms, this method will block until the application has exited. On mobile and web platforms, it returns immediately.
- Return type:
None
- property main_window: Window | str | None¶
The main window for the app.
See the documentation on assigning a main window for values that can be used for this attribute.
- on_exit()¶
The event handler that will be invoked when the app is about to exit.
The return value of this method controls whether the app is allowed to exit. This can be used to prevent the app exiting with unsaved changes, etc.
If necessary, the overridden method can be defined as an
async
coroutine.- Returns:
True
if the app is allowed to exit;False
if the app is not allowed to exit.- Return type:
- on_running()¶
The event handler that will be invoked when the app’s event loop starts running.
If necessary, the overridden method can be defined as an
async
coroutine.- Return type:
None
- property paths: Paths¶
Paths for platform-appropriate locations on the user’s file system.
Some platforms do not allow access to any file system location other than these paths. Even when arbitrary file access is allowed, there are preferred locations for each type of content.
- request_exit()¶
Request an exit from the application.
This method will call the
on_exit()
handler to confirm if the app should be allowed to exit; if that handler confirms the action, the app will exit.
- set_full_screen(*windows)¶
DEPRECATED – Use
App.enter_presentation_mode()
andApp.exit_presentation_mode()
.- Parameters:
windows (Window)
- Return type:
None
- show_cursor()¶
Make the cursor visible.
- Return type:
None
- startup()¶
Create and show the main window for the application.
Subclasses can override this method to define customized startup behavior; however, any override must ensure the
main_window
has been assigned before it returns.- Return type:
None
- property status_icons: StatusIconSet¶
The status icons displayed by the app.
- visit_homepage()¶
Open the application’s
home_page
in the default browser.This method is invoked as a handler by the “Visit homepage” default menu item. If the
home_page
isNone
, this is a no-op, and the default menu item will be disabled.- Return type:
None
- property widgets: WidgetRegistry¶
The widgets managed by the app, over all windows.
Can be used to look up widgets by ID over the entire app (e.g.,
app.widgets["my_id"]
).Only returns widgets that are currently part of a layout. A widget that has been created, but not assigned as part of window content will not be returned by widget lookup.
- protocol toga.app.AppStartupMethod¶
-
Classes that implement this protocol must have the following methods / attributes:
- __call__(app, **kwargs)¶
The startup method of the app.
Called during app startup to set the initial main window content.
- protocol toga.app.BackgroundTask¶
-
Classes that implement this protocol must have the following methods / attributes:
- protocol toga.app.OnRunningHandler¶
-
Classes that implement this protocol must have the following methods / attributes:
- protocol toga.app.OnExitHandler¶
-
Classes that implement this protocol must have the following methods / attributes:
- __call__(app, **kwargs)¶
A handler to invoke when the app is about to exit.
The return value of this callback controls whether the app is allowed to exit. This can be used to prevent the app exiting with unsaved changes, etc.