Skip to content

Input

This chapter will discuss how to make your app respond to input in the form of key presses and mouse actions.

Quote

More Input!

— Johnny Five

Keyboard input

The most fundamental way to receive input is via Key events. Let's write an app to show key events as you type.

key01.py
from textual.app import App, ComposeResult
from textual.widgets import TextLog
from textual import events


class InputApp(App):
    """App to display key events."""

    def compose(self) -> ComposeResult:
        yield TextLog()

    def on_key(self, event: events.Key) -> None:
        self.query_one(TextLog).write(event)


if __name__ == "__main__":
    app = InputApp()
    app.run()

InputApp Key(key='T'char='T') Key(key='e'char='e') Key(key='x'char='x') Key(key='t'char='t') Key(key='u'char='u') Key(key='a'char='a') Key(key='l'char='l') Key(key='exclamation_mark'char='!')

Note the key event handler on the app which logs all key events. If you press any key it will show up on the screen.

Attributes

There are two main attributes on a key event. The key attribute is the name of the key which may be a single character, or a longer identifier. Textual ensures that the key attribute could always be used in a method name.

Key events also contain a char attribute which contains a single character if it is printable, or None if it is not printable (like a function key which has no corresponding character).

To illustrate the difference between key and char, try key01.py with the space key. You should see something like the following:

InputApp Key(key='space'char=' ')

Note that the key attribute contains the word "space" while the char attribute contains a literal space.

Key methods

Textual offers a convenient way of handling specific keys. If you create a method beginning with key_ followed by the name of a key, then that method will be called in response to the key.

Let's add a key method to the example code.

key02.py
from textual.app import App, ComposeResult
from textual.widgets import TextLog
from textual import events


class InputApp(App):
    """App to display key events."""

    def compose(self) -> ComposeResult:
        yield TextLog()

    def on_key(self, event: events.Key) -> None:
        self.query_one(TextLog).write(event)

    def key_space(self) -> None:
        self.bell()


if __name__ == "__main__":
    app = InputApp()
    app.run()

Note the addition of a key_space method which is called in response to the space key, and plays the terminal bell noise.

Note

Consider key methods to be a convenience for experimenting with Textual features. In nearly all cases, key bindings and actions are preferable.

Input focus

Only a single widget may receive key events at a time. The widget which is actively receiving key events is said to have input focus.

The following example shows how focus works in practice.

key03.py
from textual.app import App, ComposeResult
from textual.widgets import TextLog
from textual import events


class KeyLogger(TextLog):
    def on_key(self, event: events.Key) -> None:
        self.write(event)


class InputApp(App):
    """App to display key events."""

    CSS_PATH = "key03.css"

    def compose(self) -> ComposeResult:
        yield KeyLogger()
        yield KeyLogger()
        yield KeyLogger()
        yield KeyLogger()


if __name__ == "__main__":
    app = InputApp()
    app.run()
key03.css
Screen {
    layout: grid;
    grid-size: 2 2;
    grid-columns: 1fr;
}

KeyLogger {  
    border: blank;
}

KeyLogger:hover {
    border: wide $secondary;
}

KeyLogger:focus {
    border: wide $accent;
}

InputApp ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ Key(key='H'char='H')Key(key='W'char='W') Key(key='e'char='e')Key(key='o'char='o') Key(key='l'char='l')Key(key='r'char='r') Key(key='l'char='l')Key(key='l'char='l') Key(key='o'char='o')Key(key='d'char='d') Key(key='tab'char='\t')Key(key='exclamation_mark'char='!' ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

The app splits the screen in to quarters, with a TextLog widget in each quarter. If you click any of the text logs, you should see that it is highlighted to show that the widget has focus. Key events will be sent to the focused widget only.

Tip

the :focus CSS pseudo-selector can be used to apply a style to the focused widget.

You can move focus by pressing the Tab key to focus the next widget. Pressing Shift+Tab moves the focus in the opposite direction.

Controlling focus

Textual will handle keyboard focus automatically, but you can tell Textual to focus a widget by calling the widget's focus() method.

Focus events

When a widget receives focus, it is sent a Focus event. When a widget loses focus it is sent a Blur event.

Bindings

Keys may be associated with actions for a given widget. This association is known as a key binding.

To create bindings, add a BINDINGS class variable to your app or widget. This should be a list of tuples of three strings. The first value is the key, the second is the action, the third value is a short human readable description.

The following example binds the keys R, G, and B to an action which adds a bar widget to the screen.

binding01.py
from textual.app import App, ComposeResult
from textual.color import Color
from textual.widgets import Footer, Static


class Bar(Static):
    pass


class BindingApp(App):

    CSS_PATH = "binding01.css"
    BINDINGS = [
        ("r", "add_bar('red')", "Add Red"),
        ("g", "add_bar('green')", "Add Green"),
        ("b", "add_bar('blue')", "Add Blue"),
    ]

    def compose(self) -> ComposeResult:
        yield Footer()

    def action_add_bar(self, color: str) -> None:
        bar = Bar(color)
        bar.styles.background = Color.parse(color).with_alpha(0.5)
        self.mount(bar)
        self.call_after_refresh(self.screen.scroll_end, animate=False)


if __name__ == "__main__":
    app = BindingApp()
    app.run()
binding01.css
Bar {
    height: 5;    
    content-align: center middle;
    text-style: bold;
    margin: 1 2;
    color: $text;
}

BindingApp red▂▂ green blue blue  R  Add Red  G  Add Green  B  Add Blue 

Note how the footer displays bindings and makes them clickable.

Tip

Multiple keys can be bound to a single action by comma-separating them. For example, ("r,t", "add_bar('red')", "Add Red") means both R and T are bound to add_bar('red').

Binding class

The tuple of three strings may be enough for simple bindings, but you can also replace the tuple with a Binding instance which exposes a few more options.

Why use bindings?

Bindings are particularly useful for configurable hot-keys. Bindings can also be inspected in widgets such as Footer.

In a future version of Textual it will also be possible to specify bindings in a configuration file, which will allow users to override app bindings.

Mouse Input

Textual will send events in response to mouse movement and mouse clicks. These events contain the coordinates of the mouse cursor relative to the terminal or widget.

Information

The trackpad (and possibly other pointer devices) are treated the same as the mouse in terminals.

Terminal coordinates are given by a pair values named x and y. The X coordinate is an offset in characters, extending from the left to the right of the screen. The Y coordinate is an offset in lines, extending from the top of the screen to the bottom.

Coordinates may be relative to the screen, so (0, 0) would be the top left of the screen. Coordinates may also be relative to a widget, where (0, 0) would be the top left of the widget itself.

eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nO1ba0/bSFx1MDAxNP3eX1x1MDAxMaVfdqUynfej0mpcdTAwMDVcdTAwMDGaQHktXHUwMDAxXG6rVeUmTmxw7GA7XHUwMDA0qPjve+1A7DxcdKHJhlXzXHUwMDAxyIxcdTAwMWbXM+ecOfeO+fGuUCjGd227+KlQtG9rlufWQ6tb/JC039hh5Fx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MDAwNeEmVVx1MDAxOCJ9 XyXy(0, 0)(0, 0)Widget

Mouse movements

When you move the mouse cursor over a widget it will receive MouseMove events which contain the coordinate of the mouse and information about what modifier keys (Ctrl, Shift etc) are held down.

The following example shows mouse movements being used to attach a widget to the mouse cursor.

mouse01.py
from textual import events
from textual.app import App, ComposeResult
from textual.containers import Container
from textual.widgets import Static, TextLog


class PlayArea(Container):
    def on_mount(self) -> None:
        self.capture_mouse()

    def on_mouse_move(self, event: events.MouseMove) -> None:
        self.screen.query_one(TextLog).write(event)
        self.query_one(Ball).offset = event.offset - (8, 2)


class Ball(Static):
    pass


class MouseApp(App):
    CSS_PATH = "mouse01.css"

    def compose(self) -> ComposeResult:
        yield TextLog()
        yield PlayArea(Ball("Textual"))


if __name__ == "__main__":
    app = MouseApp()
    app.run()
mouse01.css
Screen {
    layers: log ball;
}

TextLog {
    layer: log;
}

PlayArea { 
    background: transparent;
    layer: ball;

}
Ball {
    layer: ball;
    width: auto;
    height: 1;
    background: $secondary;
    border: tall $secondary;    
    color: $background;
    box-sizing: content-box;
    text-style: bold;
    padding: 0 4;
}

If you run mouse01.py you should find that it logs the mouse move event, and keeps a widget pinned directly under the cursor.

The on_mouse_move handler sets the offset style of the ball (a rectangular one) to match the mouse coordinates.

Mouse capture

In the mouse01.py example there was a call to capture_mouse() in the mount handler. Textual will send mouse move events to the widget directly under the cursor. You can tell Textual to send all mouse events to a widget regardless of the position of the mouse cursor by calling capture_mouse.

Call release_mouse to restore the default behavior.

Warning

If you capture the mouse, be aware you might get negative mouse coordinates if the cursor is to the left of the widget.

Textual will send a MouseCapture event when the mouse is captured, and a MouseRelease event when it is released.

Enter and Leave events

Textual will send a Enter event to a widget when the mouse cursor first moves over it, and a Leave event when the cursor moves off a widget.

Click events

There are three events associated with clicking a button on your mouse. When the button is initially pressed, Textual sends a MouseDown event, followed by MouseUp when the button is released. Textual then sends a final Click event.

If you want your app to respond to a mouse click you should prefer the Click event (and not MouseDown or MouseUp). This is because a future version of Textual may support other pointing devices which don't have up and down states.

Scroll events

Most mice have a scroll wheel which you can use to scroll the window underneath the cursor. Scrollable containers in Textual will handle these automatically, but you can handle MouseScrollDown and MouseScrollUp if you want build your own scrolling functionality.

Information

Terminal emulators will typically convert trackpad gestures in to scroll events.