Skip to content

On

Decorator to declare that the method is a message handler.

The decorator accepts an optional CSS selector that will be matched against a widget exposed by a control property on the message.

Example
# Handle the press of buttons with ID "#quit".
@on(Button.Pressed, "#quit")
def quit_button(self) -> None:
    self.app.quit()

Keyword arguments can be used to match additional selectors for attributes listed in ALLOW_SELECTOR_MATCH.

Example
# Handle the activation of the tab "#home" within the `TabbedContent` "#tabs".
@on(TabbedContent.TabActivated, "#tabs", tab="#home")
def switch_to_home(self) -> None:
    self.log("Switching back to the home tab.")
    ...
Parameters
Parameter Default Description
message_type
type[Message]
required

The message type (i.e. the class).

selector
str | None
None

An optional selector. If supplied, the handler will only be called if selector matches the widget from the control attribute of the message.

**kwargs
str
{}

Additional selectors for other attributes of the message.