File tree Expand file tree Collapse file tree 2 files changed +34
-15
lines changed Expand file tree Collapse file tree 2 files changed +34
-15
lines changed Original file line number Diff line number Diff line change 1+ from textual .app import App , ComposeResult
2+ from textual .binding import Binding
3+ from textual .reactive import reactive
4+ from textual .widgets import Static
5+
6+
7+ class Counter (Static , can_focus = True ):
8+ """A counter that can be incremented and decremented by pressing keys."""
9+
10+ BINDINGS = [
11+ Binding ("up" , "change_count(1)" , "Increment" ),
12+ Binding ("down" , "change_count(-1)" , "Decrement" ),
13+ ]
14+
15+ count = reactive (0 )
16+
17+ def render (self ) -> str :
18+ return f"Count: { self .count } "
19+
20+ def action_change_count (self , amount : int ) -> None :
21+ self .count += amount
22+
23+
24+ class CalculatorApp (App [None ]):
25+ def compose (self ) -> ComposeResult :
26+ yield Counter ()
27+ yield Counter ()
28+
29+
30+ if __name__ == "__main__" :
31+ app = CalculatorApp ()
32+ app .run ()
Original file line number Diff line number Diff line change @@ -53,29 +53,16 @@ The addition of the CSS has completely transformed our custom widget.
5353
5454### Responding to key presses
5555
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.
56+ Widgets can have a list of associated key [ bindings] ( ../guide/input.md#bindings ) ,
57+ which enable a it to call [ actions] ( ../guide/actions.md ) in response to key presses.
5858
5959A widget's bindings will only be checked if it or one of its descendants has focus.
6060
6161Let's look at Textual's builtin [ Button] ( ../widgets/button.md ) widget to see an example of how widget bindings work.
6262The ` Button ` widget has a single binding for the ` enter ` key.
6363When a button is focused, and the user presses ++enter++, the ` action_press ` method inside ` Button ` is called.
6464
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.
7665
77- Note that widgets cannot be focused by default.
78- Setting ` can_focus=True ` is required to make a widget focusable.
7966
8067## Static widget
8168
You can’t perform that action at this time.
0 commit comments