Skip to content

Commit 6f6c987

Browse files
committed
Docs example
1 parent 4dec4b3 commit 6f6c987

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

docs/guide/widgets.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,32 @@ The addition of the CSS has completely transformed our custom widget.
5151
```{.textual path="docs/examples/guide/widgets/hello02.py"}
5252
```
5353

54+
### Responding to key presses
55+
56+
Widgets can have a list of key [bindings](../guide/input.md#bindings) associated with them.
57+
This enables a widget to call [actions](../guide/actions.md) in response to key presses.
58+
59+
A widget's bindings will only be checked if it or one of its descendants has focus.
60+
61+
Let's look at Textual's builtin [Button](../widgets/button.md) widget to see an example of how widget bindings work.
62+
The `Button` widget has a single binding for the `enter` key.
63+
When a button is focused, and the user presses ++enter++, the `action_press` method inside button is called.
64+
65+
```python
66+
class Button(Widget, can_focus=True): # (1)!
67+
BINDINGS = [Binding("enter", "press", "Press Button", show=False)] # (2)!
68+
# ...
69+
def action_press(self) -> None: # (3)!
70+
self.press()
71+
```
72+
73+
1. The `Button` has `can_focus=True` to ensure it can be focused and therefore handle bindings.
74+
2. It has a binding which associates the ++enter++ key with the `action_press` method.
75+
3. `action_press` will be called when the user presses ++enter++ while the button is focused.
76+
77+
Note that widgets cannot be focused by default.
78+
Setting `can_focus=True` is required to make a widget focusable.
79+
5480
## Static widget
5581

5682
While you can extend the Widget class, a subclass will typically be a better starting point. The [Static][textual.widgets.Static] class is a widget subclass which caches the result of render, and provides an [update()][textual.widgets.Static.update] method to update the content area.

0 commit comments

Comments
 (0)