App¶
The top-level representation of an application.
Availability (Key)
| macOS | GTK | Windows | iOS | Android | Web | Terminal |
|---|---|---|---|---|---|---|
| ● | ● | ● | ● | ● | ○ | ○ |
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.
toga.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.
toga.App.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:Trueif the app is allowed to exit;Falseotherwise. 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¶
toga.App ¶
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
App.main_loop() method, which will start the event loop
of your App.
| PARAMETER | DESCRIPTION |
|---|---|
formal_name
|
The human-readable name of the app. If not provided, the metadata key
TYPE:
|
app_id
|
The unique application identifier. This will usually be a reversed domain name, e.g.
TYPE:
|
app_name
|
The name of the distribution used to load metadata with
TYPE:
|
icon
|
The icon for the app. Defaults to
TYPE:
|
author
|
The person or organization to be credited as the author of the app. If not provided, the metadata key
TYPE:
|
version
|
The version number of the app. If not provided, the metadata key
TYPE:
|
home_page
|
The URL of a web page for the app. Used in auto-generated help menu items. If not provided, the metadata key
TYPE:
|
description
|
A brief (one line) description of the app. If not provided, the metadata key
TYPE:
|
startup
|
A callable to run before starting the app.
TYPE:
|
on_running
|
The initial
TYPE:
|
on_exit
|
The initial
TYPE:
|
document_types
|
A list of |
BACKGROUND
class-attribute
instance-attribute
¶
BACKGROUND
A constant that can be used as the main window to indicate that an app will run in the background without a main window.
app
class-attribute
instance-attribute
¶
app
The currently running App. Since there can only be one running
Toga app in a process, this is available as a class property via
toga.App.app. If no app has been created yet, this is set to None.
app_id
property
¶
app_id
The unique application identifier (read-only). This will usually be a
reversed domain name, e.g. org.beeware.myapp.
app_name
property
¶
app_name
The name of the distribution used to load metadata with
importlib.metadata (read-only).
author
property
¶
author
The person or organization to be credited as the author of the app (read-only).
dark_mode
property
¶
dark_mode
Whether the user has dark mode enabled in their environment (read-only).
| RETURNS | DESCRIPTION |
|---|---|
bool | None
|
A Boolean describing if the app is in dark mode; |
home_page
property
¶
home_page
The URL of a web page for the app (read-only). Used in auto-generated help menu items.
is_bundled
property
¶
is_bundled
Has the app been bundled as a standalone binary, or is it running as a Python script?
main_window
property
writable
¶
main_window
The main window for the app.
See the documentation on assigning a main window for values that can be used for this attribute.
paths
property
¶
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.
widgets
property
¶
widgets
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.
windows
property
¶
windows
The windows managed by the app. Windows are automatically added to the app when they are created, and removed when they are closed.
about ¶
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.
add_background_task ¶
add_background_task(handler)
DEPRECATED – Use asyncio.create_task, or override/assign
App.on_running().
dialog
async
¶
dialog(dialog)
enter_presentation_mode ¶
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.
| PARAMETER | DESCRIPTION |
|---|---|
windows
|
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 | DESCRIPTION |
|---|---|
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. |
exit ¶
exit()
Unconditionally exit the application.
This does not invoke the on_exit handler; the app will be immediately
and unconditionally closed.
main_loop ¶
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.
on_exit ¶
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 | DESCRIPTION |
|---|---|
bool
|
|
on_running ¶
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.
request_exit ¶
request_exit()
Request an exit from the application.
This method will call the App.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 ¶
set_full_screen(*windows)
DEPRECATED – Use
App.enter_presentation_mode() and
App.exit_presentation_mode().
startup ¶
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.
toga.app.AppStartupMethod ¶
Bases: Protocol
__call__ ¶
__call__(app, **kwargs)
The startup method of the app.
Called during app startup to set the initial main window content.
| PARAMETER | DESCRIPTION |
|---|---|
app
|
The app instance that is starting.
TYPE:
|
kwargs
|
Ensures compatibility with additional arguments introduced in future versions.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Widget
|
The widget to use as the main window content. |
toga.app.BackgroundTask ¶
toga.app.OnRunningHandler ¶
toga.app.OnExitHandler ¶
Bases: Protocol
__call__ ¶
__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.
| PARAMETER | DESCRIPTION |
|---|---|
app
|
The app instance that is exiting.
TYPE:
|
kwargs
|
Ensures compatibility with additional arguments introduced in future versions.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|