This commit is contained in:
Will McGugan
2023-02-23 14:37:47 +00:00
parent 4cf7492a28
commit 2ee61f95db
2 changed files with 29 additions and 3 deletions

View File

@@ -108,7 +108,7 @@ The message class is defined within the widget class itself. This is not strictl
- It creates a namespace for the handler. So rather than `on_selected`, the handler name becomes `on_color_button_selected`. This makes it less likely that your chosen name will clash with another message.
## Sending events
## Sending messages
In the previous example we used [post_message()][textual.message_pump.MessagePump.post_message] to send an event to its parent. We could also have used [post_message_no_wait()][textual.message_pump.MessagePump.post_message_no_wait] for non async code. Sending messages in this way allows you to write custom widgets without needing to know in what context they will be used.
@@ -118,6 +118,32 @@ There are other ways of sending (posting) messages, which you may need to use le
- [post_message_no_wait][textual.message_pump.MessagePump.post_message_no_wait] The non-async version of `post_message`.
## Preventing messages
You can *temporarily* prevent a Widget or App from posting messages or events of a particular type by calling [prevent][textual.message_pump.MessagePump.prevent], which returns a context manager. This is typically used when updating data in a child widget and you don't want to receive notifications that something has changed.
The following example will play the terminal bell as you type, by handling the [Input.Changed][textual.widgets.Input.Changed] event. There's also a button to clear the input by setting `input.value` to empty string. We don't want to play the bell when the button is clicked so we wrap setting the attribute with a call to [prevent][textual.message_pump.MessagePump.prevent].
!!! tip
In reality, playing the terminal bell as you type would be very irritating -- we don't recommend it!
=== "prevent.py"
```python title="prevent.py"
--8<-- "docs/examples/events/prevent.py"
```
1. Clear the input without sending an Input.Changed event.
2. Plays the terminal sound when typing.
=== "Output"
```{.textual path="docs/examples/events/prevent.py"}
```
## Message handlers
Most of the logic in a Textual app will be written in message handlers. Let's explore handlers in more detail.