Skip to content

Commit

Permalink
Simplify wording, add counter example
Browse files Browse the repository at this point in the history
  • Loading branch information
darrenburns committed Sep 24, 2024
1 parent 3e1b413 commit 0fb0e2b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 15 deletions.
32 changes: 32 additions & 0 deletions docs/examples/guide/widgets/bindings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.reactive import reactive
from textual.widgets import Static


class Counter(Static, can_focus=True):
"""A counter that can be incremented and decremented by pressing keys."""

BINDINGS = [
Binding("up", "change_count(1)", "Increment"),
Binding("down", "change_count(-1)", "Decrement"),
]

count = reactive(0)

def render(self) -> str:
return f"Count: {self.count}"

def action_change_count(self, amount: int) -> None:
self.count += amount


class CalculatorApp(App[None]):
def compose(self) -> ComposeResult:
yield Counter()
yield Counter()


if __name__ == "__main__":
app = CalculatorApp()
app.run()
17 changes: 2 additions & 15 deletions docs/guide/widgets.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,29 +53,16 @@ The addition of the CSS has completely transformed our custom widget.

### Responding to key presses

Widgets can have a list of key [bindings](../guide/input.md#bindings) associated with them.
This enables a widget to call [actions](../guide/actions.md) in response to key presses.
Widgets can have a list of associated key [bindings](../guide/input.md#bindings),
which enable a it to call [actions](../guide/actions.md) in response to key presses.

A widget's bindings will only be checked if it or one of its descendants has focus.

Let's look at Textual's builtin [Button](../widgets/button.md) widget to see an example of how widget bindings work.
The `Button` widget has a single binding for the `enter` key.
When a button is focused, and the user presses ++enter++, the `action_press` method inside `Button` is called.

```python
class Button(Widget, can_focus=True): # (1)!
BINDINGS = [Binding("enter", "press", "Press Button", show=False)] # (2)!
# ...
def action_press(self) -> None: # (3)!
self.press()
```

1. The `Button` has `can_focus=True` to ensure it can be focused and therefore handle bindings.
2. It has a binding which associates the ++enter++ key with the `action_press` method.
3. `action_press` will be called when the user presses ++enter++ while the button is focused.

Note that widgets cannot be focused by default.
Setting `can_focus=True` is required to make a widget focusable.

## Static widget

Expand Down

0 comments on commit 0fb0e2b

Please sign in to comment.