mirror of
https://github.com/Textualize/textual.git
synced 2025-10-17 02:38:12 +03:00
event docs
This commit is contained in:
48
docs/examples/events/custom01.py
Normal file
48
docs/examples/events/custom01.py
Normal file
@@ -0,0 +1,48 @@
|
||||
from textual.app import App, ComposeResult
|
||||
from textual.color import Color
|
||||
from textual.message import Message, MessageTarget
|
||||
from textual.widgets import Static
|
||||
|
||||
|
||||
class ColorButton(Static):
|
||||
"""A color button."""
|
||||
|
||||
class Selected(Message):
|
||||
"""Color selected message."""
|
||||
|
||||
def __init__(self, sender: MessageTarget, color: Color) -> None:
|
||||
self.color = color
|
||||
super().__init__(sender)
|
||||
|
||||
def __init__(self, color: Color) -> None:
|
||||
self.color = color
|
||||
super().__init__()
|
||||
|
||||
def on_mount(self) -> None:
|
||||
self.styles.margin = (1, 2)
|
||||
self.styles.content_align = ("center", "middle")
|
||||
self.styles.background = Color.parse("#ffffff33")
|
||||
self.styles.border = ("tall", self.color)
|
||||
|
||||
async def on_click(self) -> None:
|
||||
# The emit method sends an event to a widget's parent
|
||||
await self.emit(self.Selected(self, self.color))
|
||||
|
||||
def render(self) -> str:
|
||||
return str(self.color)
|
||||
|
||||
|
||||
class ColorApp(App):
|
||||
def compose(self) -> ComposeResult:
|
||||
yield ColorButton(Color.parse("#008080"))
|
||||
yield ColorButton(Color.parse("#808000"))
|
||||
yield ColorButton(Color.parse("#E9967A"))
|
||||
yield ColorButton(Color.parse("#121212"))
|
||||
|
||||
def on_color_button_selected(self, message: ColorButton.Selected) -> None:
|
||||
self.screen.styles.animate("background", message.color, duration=0.5)
|
||||
|
||||
|
||||
app = ColorApp()
|
||||
if __name__ == "__main__":
|
||||
app.run()
|
||||
@@ -2,7 +2,7 @@ All you need to get started building Textual apps.
|
||||
|
||||
## Requirements
|
||||
|
||||
Textual requires Python 3.7 or later. Textual runs on Linux, MacOS, Windows and probably any OS where Python also runs.
|
||||
Textual requires Python 3.7 or later (if you have a choice, pick the most recent Python). Textual runs on Linux, MacOS, Windows and probably any OS where Python also runs.
|
||||
|
||||
!!! info inline end "Your platform"
|
||||
|
||||
|
||||
@@ -2,9 +2,13 @@
|
||||
|
||||
We've used event handler methods in many of the examples in this guide. This chapter explores events and messages (see below) in more detail.
|
||||
|
||||
!!! tip
|
||||
|
||||
See [events](../events/index.md) for a comprehensive reference on the events Textual sends.
|
||||
|
||||
## Messages
|
||||
|
||||
Events are a particular kind of *message* which is sent by Textual in response to input and other state changes. Events are reserved for use by Textual but you can also create custom messages for the purpose of coordinating between widgets in your app.
|
||||
Events are a particular kind of *message* sent by Textual in response to input and other state changes. Events are reserved for use by Textual but you can also create custom messages for the purpose of coordinating between widgets in your app.
|
||||
|
||||
More on that later, but for now keep in mind that events are also messages, and anything that is true of messages is true of events.
|
||||
|
||||
@@ -36,29 +40,23 @@ When the `on_key` method returns, Textual will get the next event off the the qu
|
||||
--8<-- "docs/images/events/queue2.excalidraw.svg"
|
||||
</div>
|
||||
|
||||
## Creating Messages
|
||||
|
||||
## Handlers
|
||||
|
||||
|
||||
### Naming
|
||||
|
||||
Let's explore how Textual decides what method to call for a given event.
|
||||
|
||||
- Start with `"on_"`.
|
||||
- Add the messages namespace (if any) converted from CamelCase to snake_case plus an underscore `"_"`
|
||||
- Add the name of the class converted from CamelCase to snake_case.
|
||||
|
||||
### Default behaviors
|
||||
## Default behaviors
|
||||
|
||||
You may be familiar with Python's [super](https://docs.python.org/3/library/functions.html#super) function to call a function defined in a base class. You will not have to do this for Textual event handlers as Textual will automatically call any handler methods defined in the base class.
|
||||
|
||||
For instance if you define a custom widget, Textual will call its `on_key` handler when you hit a key. Textual will also run any `on_key` methods found in the widget's base classes, including `Widget.on_key` where key bindings are processed. Without this behavior, you would have to remember to call `super().on_key(event)` or key bindings would break.
|
||||
For instance if you define a custom widget, Textual will call its `on_key` handler when you hit a key. Textual will also run any `on_key` methods found in the widget's base classes, including `Widget.on_key` where key bindings are processed. Without this behavior, you would have to remember to call `super().on_key(event)` on all key handlers or key bindings would break.
|
||||
|
||||
### Preventing default behaviors
|
||||
|
||||
If you don't want this behavior you can call [prevent_default()][textual.message.Message.prevent_default] on the event object. This tells Textual not to call any handlers on base classes.
|
||||
|
||||
!!! warning
|
||||
|
||||
### Bubbling
|
||||
Don't call `prevent_default` lightly. It *may* break some of Textual's standard features.
|
||||
|
||||
|
||||
## Bubbling
|
||||
|
||||
Messages have a `bubble` attribute. If this is set to `True` then events will be sent to their parent widget. Input events typically bubble so that a widget will have the opportunity to process events after its children.
|
||||
|
||||
@@ -68,13 +66,13 @@ The following diagram shows an (abbreviated) DOM for a UI with a container and t
|
||||
--8<-- "docs/images/events/bubble1.excalidraw.svg"
|
||||
</div>
|
||||
|
||||
After Textual calls `Button.on_key` it _bubbles_ the event to its parent and call `Container.on_key` (if it exists).
|
||||
After Textual calls `Button.on_key` the event _bubbles_ to the buttons parent and will call `Container.on_key` (if it exists).
|
||||
|
||||
<div class="excalidraw">
|
||||
--8<-- "docs/images/events/bubble2.excalidraw.svg"
|
||||
</div>
|
||||
|
||||
Then it will bubble to the container's parent (the App class).
|
||||
As before, the event bubbles to it's parent (the App class).
|
||||
|
||||
<div class="excalidraw">
|
||||
--8<-- "docs/images/events/bubble3.excalidraw.svg"
|
||||
@@ -82,17 +80,54 @@ Then it will bubble to the container's parent (the App class).
|
||||
|
||||
The App class is always the root of the DOM, so there is no where for the event to bubble to.
|
||||
|
||||
#### Stopping bubbling
|
||||
### Stopping bubbling
|
||||
|
||||
Event handlers may stop this bubble behavior by calling the [stop()][textual.message.Message.stop] method on the event or message. You might want to do this if a widget has responded to the event in an authoritative way. For instance if a text input widget as responded to a key event you probably do not want it to also invoke a key binding.
|
||||
Event handlers may stop this bubble behavior by calling the [stop()][textual.message.Message.stop] method on the event or message. You might want to do this if a widget has responded to the event in an authoritative way. For instance if a text input widget responded to a key event you probably do not want it to also invoke a key binding.
|
||||
|
||||
## Custom messages
|
||||
|
||||
You can create custom messages for your application that may be used in the same way as events (recall that events are simply messages reserved for use by Textual).
|
||||
|
||||
The most common reason to do this is if you are building a custom widget and you need to inform a parent widget about a state change.
|
||||
|
||||
Let's look at an example which defines a custom message. The following example creates color buttons which, when clicked, send a custom message.
|
||||
|
||||
=== "custom01.py"
|
||||
|
||||
```python title="custom01.py" hl_lines="10-15 27-29 42-43"
|
||||
--8<-- "docs/examples/events/custom01.py"
|
||||
```
|
||||
=== "Output"
|
||||
|
||||
```{.textual path="docs/examples/events/custom01.py"}
|
||||
```
|
||||
|
||||
|
||||
Note the custom message class which extends [Message][textual.message.Message]. The constructor stores a [color][textual.color.Color] object which handler methods will be able to inspect.
|
||||
|
||||
<hr>
|
||||
TODO: events docs
|
||||
The message class is defined within the widget class itself. This is not strictly required but recommended.
|
||||
|
||||
- If reduces the amount of imports. If you were to import ColorButton, you have access to the message class via `ColorButton.Selected`.
|
||||
- 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.
|
||||
|
||||
### Handler naming
|
||||
|
||||
Let's recap on the scheme that Textual uses to map messages classes on to a Python method name.
|
||||
|
||||
- Start with `"on_"`.
|
||||
- Add the messages namespace (if any) converted from CamelCase to snake_case plus an underscore `"_"`
|
||||
- Add the name of the class converted from CamelCase to snake_case.
|
||||
|
||||
<div class="excalidraw">
|
||||
--8<-- "docs/images/events/naming.excalidraw.svg"
|
||||
</div>
|
||||
|
||||
### Sending events
|
||||
|
||||
In the previous example we used [emit()][textual.message_pump.MessagePump.emit] to send an event to it's parent. We could also have used [emit_no_wait()][textual.message_pump.MessagePump.emit_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.
|
||||
|
||||
There are other ways of sending (posting) messages, which you may need to use less frequently.
|
||||
|
||||
- [post_message][textual.message_pump.MessagePump.post_message] To post a message to a particular event.
|
||||
- [post_message_no_wait][textual.message_pump.MessagePump.post_message_no_wait] The non-async version of `post_message`.
|
||||
|
||||
- What are events
|
||||
- Handling events
|
||||
- Auto calling base classes
|
||||
- Event bubbling
|
||||
- Posting / emitting events
|
||||
|
||||
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 42 KiB After Width: | Height: | Size: 42 KiB |
16
docs/images/events/naming.excalidraw.svg
Normal file
16
docs/images/events/naming.excalidraw.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 12 KiB |
@@ -59,7 +59,7 @@ Textual is a framework for building applications that run within your terminal.
|
||||
<hr>
|
||||
|
||||
|
||||
```{.textual path="examples/calculator.py" columns=100 lines=40}
|
||||
```{.textual path="examples/calculator.py" columns=100 lines=41 press="3,.,1,4,5,9,2,_,_"}
|
||||
|
||||
```
|
||||
|
||||
@@ -70,6 +70,9 @@ Textual is a framework for building applications that run within your terminal.
|
||||
```{.textual path="docs/examples/tutorial/stopwatch.py" press="tab,enter,_,_"}
|
||||
```
|
||||
|
||||
```{.textual path="docs/examples/guide/layout/combining_layouts.py"}
|
||||
```
|
||||
|
||||
```{.textual path="docs/examples/app/widgets01.py"}
|
||||
```
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ By the end of this page you should have a solid understanding of app development
|
||||
|
||||
!!! quote
|
||||
|
||||
I've always thought the secret sauce in making a popular framework is for it to be fun.
|
||||
If you want people to build things, make it fun.
|
||||
|
||||
— **Will McGugan** (creator of Rich and Textual)
|
||||
|
||||
@@ -329,7 +329,7 @@ The `on_button_pressed` method is an *event handler*. Event handlers are methods
|
||||
|
||||
If you run "stopwatch04.py" now you will be able to toggle between the two states by clicking the first button:
|
||||
|
||||
```{.textual path="docs/examples/tutorial/stopwatch04.py" title="stopwatch04.py" press="tab,tab,tab,enter,_,_"}
|
||||
```{.textual path="docs/examples/tutorial/stopwatch04.py" title="stopwatch04.py" press="tab,tab,tab,_,enter,_,_,_"}
|
||||
```
|
||||
|
||||
## Reactive attributes
|
||||
|
||||
Reference in New Issue
Block a user