Skip to content
Toga
0.5.3.dev143+gabcc6cdb6

Command

A representation of app functionality that the user can invoke from menus or toolbars.

Availability (Key)

macOS GTK Windows iOS Android Web Terminal

Usage

Aside from event handlers on widgets, most GUI toolkits also provide other ways for the user to give instructions to an app. In Toga, these UI patterns are supported by the Command class.

A command encapsulates a piece of functionality that the user can invoke - no matter how they invoke it. It doesn't matter if they select a menu item, press a button on a toolbar, or use a key combination - the functionality is wrapped up in a Command.

Adding commands

Commands are added to an app using the properties toga.App.commands and toga.MainWindow.toolbar. Toga then takes control of ensuring that the command is exposed to the user in a way that they can access. On desktop platforms, this may result in a command being added to a menu.

Commands can be organized into a Group of similar commands. Groups are hierarchical, so a group can contain a sub-group, which can contain a sub-group, and so on. Inside a group, commands can be organized into sections.

For example:

import toga

def callback(sender, **kwargs):
    print("Command activated")

stuff_group = toga.Group('Stuff', order=40)

cmd1 = toga.Command(
    callback,
    text='Example command',
    tooltip='Tells you when it has been activated',
    shortcut=toga.Key.MOD_1 + 'k',
    icon='icons/pretty.png',
    group=stuff_group,
    section=0
)
cmd2 = toga.Command(
    ...
)
...

app.commands.add(cmd1, cmd4, cmd3)
app.main_window.toolbar.add(cmd2, cmd3)

This code defines a command cmd1 that will be placed in the first section of the "Stuff" group. It can be activated by pressing CTRL-k (or CMD-K on a Mac).

The definitions for cmd2, cmd3, and cmd4 have been omitted, but would follow a similar pattern.

It doesn't matter what order you add commands to the app - the group, section and order will be used to display the commands in the right order.

If a command is added to a toolbar, it will automatically be added to the app as well. It isn't possible to have functionality exposed on a toolbar that isn't also exposed by the app. So, cmd2 will be added to the app, even though it wasn't explicitly added to the app commands.

Removing commands

Commands can be removed using set-like and dictionary-like APIs. The set-like APIs use the command instance; the dictionary-like APIs use the command ID:

# Remove the app using the instance
app.commands.remove(cmd_1)

# Remove a command by ID
del app.commands["Some-Command-ID"]

Standard commands

Each command has an id attribute. This is set when the command is defined; if no ID is provided, a random ID will be generated for the Command. This identifier can be used to retrieve a command from toga.App.commands and toga.MainWindow.toolbar.

These command IDs are also used to create standard commands. These are commands that are expected functionality in most applications, such as ABOUT and EXIT, as well as document management commands such as NEW, OPEN and SAVE.

These commands are automatically added to your app, depending on platform requirements and app definition. For example, mobile apps won't have an Exit command as mobile apps don't have a concept of "exiting". Document management commands will be automatically added if your app defines document types.

The label, shortcut, grouping and ordering of these commands is platform dependent. For example, on macOS, the EXIT command will be labeled "Quit My App", and have a shortcut of Command-q; on Windows, the command will be labeled "Exit", and won't have a keyboard shortcut.

Any automatically added standard commands will be installed before your app's startup() method is invoked. If you wish to remove or modify and a standard app command, you can use the standard command's ID to retrieve the command instance from toga.App.commands. If you wish to add or override a standard command that hasn't been installed by default (for example, to add an Open command without defining a document type), you can use the toga.Command.standard() method to create an instance of the standard command, and add that command to your app:

import toga

class MyApp(toga.app):
    def startup(self):
        ...
        # Delete the default Preferences command
        del self.commands[toga.Command.PREFERENCES]

        # Modify the text of the "About" command
        self.commands[toga.Command.ABOUT].text = "I'm Customized!!"

        # Add an Open command
        custom_open = toga.Command.standard(
            self,
            toga.Command.OPEN,
            action=self.custom_open
        )

        self.commands.add(custom_open)

Reference

toga.Command

Command(
    action,
    text,
    *,
    shortcut=None,
    tooltip=None,
    icon=None,
    group=Group.COMMANDS,
    section=0,
    order=0,
    enabled=True,
    id=None,
)

Create a new Command.

Commands may not use all the arguments - for example, on some platforms, menus will contain icons; on other platforms they won't.

PARAMETER DESCRIPTION
action

A handler to invoke when the command is activated. If this is None, the command will be disabled.

TYPE: ActionHandler | None

text

A label for the command.

TYPE: str

shortcut

A key combination that can be used to invoke the command.

TYPE: str | Key | None DEFAULT: None

tooltip

A short description of what the command will do.

TYPE: str | None DEFAULT: None

icon

The icon content that can be used to decorate the command if the platform requires.

TYPE: IconContentT | None DEFAULT: None

group

The group to which this command belongs.

TYPE: Group DEFAULT: COMMANDS

section

The section where the command should appear within its group.

TYPE: int DEFAULT: 0

order

The position where the command should appear within its section. If multiple items have the same group, section and order, they will be sorted alphabetically by their text.

TYPE: int DEFAULT: 0

enabled

Is the Command currently enabled?

TYPE: bool DEFAULT: True

id

A unique identifier for the command.

TYPE: str DEFAULT: None

ABOUT class-attribute instance-attribute

ABOUT

An identifier for the standard "About" menu item. This command is always installed by default. Uses toga.App.about() as the default action.

EXIT class-attribute instance-attribute

EXIT

An identifier for the standard "Exit" menu item. This command may be installed by default, depending on platform requirements. Uses toga.App.request_exit() as the default action.

NEW class-attribute instance-attribute

NEW

An identifier for the standard "New" menu item. This constant will be used for the default document type for your app; if you specify more than one document type, the command for the subsequent commands will have a colon and the first extension for that data type appended to the ID. Uses toga.documents.DocumentSet.new() as the default action.

OPEN class-attribute instance-attribute

OPEN

An identifier for the standard "Open" menu item. This command will be automatically installed if your app declares any document types. Uses toga.documents.DocumentSet.request_open() as the default action.

PREFERENCES class-attribute instance-attribute

PREFERENCES

An identifier for the standard "Preferences" menu item. The Preferences item is not installed by default. If you install it manually, it will attempt to use toga.App.preferences() as the default action; your app will need to define this method, or provide an explicit value for the action.

SAVE class-attribute instance-attribute

SAVE

An identifier for the standard "Save" menu item. This command will be automatically installed if your app declares any document types. Uses toga.documents.DocumentSet.save() as the default action.

SAVE_ALL class-attribute instance-attribute

SAVE_ALL

An identifier for the standard "Save All" menu item. This command will be automatically installed if your app declares any document types. Uses toga.documents.DocumentSet.save_all() as the default action.

SAVE_AS class-attribute instance-attribute

SAVE_AS

An identifier for the standard "Save As..." menu item. This command will be automatically installed if your app declares any document types. Uses toga.documents.DocumentSet.save_as() as the default action.

VISIT_HOMEPAGE class-attribute instance-attribute

VISIT_HOMEPAGE

An identifier for the standard "Visit Homepage" menu item. This command may be installed by default, depending on platform requirements. Uses toga.App.visit_homepage() as the default action.

action property writable

action

The Action attached to the command.

enabled property writable

enabled

Is the command currently enabled?

icon property writable

icon

The Icon for the command.

Can be specified as any valid icon content.

id property

id

A unique identifier for the command.

key property

key

A unique tuple describing the path to this command.

Each element in the tuple describes the (section, order, text) for the groups that must be navigated to invoke this action.

standard classmethod

standard(app, id, **kwargs)

Create an instance of a standard command for the provided app.

The default action for the command will be constructed using the value of the command's ID as an attribute of the app object. If a method or co-routine matching that name doesn't exist, a value of None will be used as the default action.

PARAMETER DESCRIPTION
app

The app for which the standard command will be created.

TYPE: App

id

The ID of the standard command to create.

kwargs

Overrides for any default properties of the standard command. Accepts the same arguments as the Command constructor.

DEFAULT: {}

toga.Group

Group(text, *, parent=None, section=0, order=0, id=None)

A collection of commands to display together.

PARAMETER DESCRIPTION
text

A label for the group.

TYPE: str

parent

The parent of this group; use None to make a root group.

TYPE: Group | None DEFAULT: None

section

The section where the group should appear within its parent. A section cannot be specified unless a parent is also specified.

TYPE: int DEFAULT: 0

order

The position where the group should appear within its section. If multiple items have the same group, section and order, they will be sorted alphabetically by their text.

TYPE: int DEFAULT: 0

id

A unique identifier for the group.

TYPE: str | None DEFAULT: None

APP instance-attribute

APP

Application-level commands

COMMANDS instance-attribute

COMMANDS

Default group for user-provided commands

EDIT instance-attribute

EDIT

Editing commands

FILE instance-attribute

FILE

File commands

HELP instance-attribute

HELP

Help commands

VIEW instance-attribute

VIEW

Content appearance commands

WINDOW instance-attribute

WINDOW

Window management commands

id property

id

A unique identifier for the group.

key property

key

A unique tuple describing the path to this group.

parent property writable

parent

The parent of this group; returns None if the group is a root group.

root property

root

The root group for this group.

This will be self if the group is a root group.

text property

text

A text label for the group.

is_child_of

is_child_of(parent)

Is this group a child of the provided group, directly or indirectly?

PARAMETER DESCRIPTION
parent

The potential parent to check

TYPE: Group | None

RETURNS DESCRIPTION
bool

True if this group is a child of the provided parent.

is_parent_of

is_parent_of(child)

Is this group a parent of the provided group, directly or indirectly?

PARAMETER DESCRIPTION
child

The potential child to check

TYPE: Group | None

RETURNS DESCRIPTION
bool

True if this group is a parent of the provided child.

toga.command.CommandSet

CommandSet(on_change=None, app=None)

Bases: MutableSet[Command], MutableMapping[str, Command]

A collection of commands.

This is used as an internal representation of Menus, Toolbars, and any other graphical manifestations of commands. You generally don't need to construct a CommandSet of your own; you should use existing app or window level CommandSet instances.

The in operator can be used to evaluate whether a Command is a member of the CommandSet, using either an instance of a Command, or the ID of a command.

Commands can be retrieved from the CommandSet using [] notation with the requested command's ID.

When iterated over, a CommandSet returns Command instances in their sort order, with Separator instances inserted between groups.

PARAMETER DESCRIPTION
on_change

A method that should be invoked when this CommandSet changes.

TYPE: CommandSetChangeHandler | None DEFAULT: None

app

The app this CommandSet is associated with, if it is not the app's own CommandSet.

TYPE: App | None DEFAULT: None

app property

app

The app this CommandSet is associated with.

Returns None if this is the app's CommandSet.

add

add(*commands)

Add a collection of commands to the command set.

A command value of None will be ignored. This allows you to add standard commands to a command set without first validating that the platform provides an implementation of that command.

PARAMETER DESCRIPTION
commands

The commands to add to the command set.

TYPE: Command | None DEFAULT: ()

clear

clear()

Remove all commands from the command set.

toga.command.Separator

Separator(group=None)

A representation of a separator between sections in a Group.

PARAMETER DESCRIPTION
group

The group that contains the separator.

TYPE: Group | None DEFAULT: None

toga.command.ActionHandler

Bases: Protocol

__call__

__call__(command, **kwargs)

A handler that will be invoked when a Command is invoked.

PARAMETER DESCRIPTION
command

The command that triggered the action.

TYPE: Command

kwargs

Ensures compatibility with additional arguments introduced in future versions.

DEFAULT: {}

toga.command.CommandSetChangeHandler

Bases: Protocol

__call__

__call__(**kwargs)

A handler that will be invoked when a Command or Group is added to the CommandSet.

PARAMETER DESCRIPTION
kwargs

Ensures compatibility with arguments added in future versions.

DEFAULT: {}