Skip to content

KeyboardListener

Examples#

Press any keys#

import flet as ft


async def main(page: ft.Page):
    pressed_keys = set()

    def key_down(e: ft.KeyDownEvent):
        pressed_keys.add(e.key)
        keys.controls = [ft.Text(k, size=20) for k in pressed_keys]

    def key_up(e: ft.KeyUpEvent):
        pressed_keys.remove(e.key)
        keys.controls = [ft.Text(k, size=20) for k in pressed_keys]

    page.add(
        ft.Text("Press any keys..."),
        ft.KeyboardListener(
            content=(keys := ft.Row()),
            autofocus=True,
            on_key_down=key_down,
            on_key_up=key_up,
        ),
    )


ft.run(main)

KeyboardListener #

Bases: Control

A control that calls a callback whenever the user presses or releases a key on a keyboard.

autofocus #

autofocus: bool = False

True if this control will be selected as the initial focus when no other node in its scope is currently focused.

content #

content: Control

The content control of the keyboard listener.

include_semantics #

include_semantics: bool = True

Include semantics information in this control.

on_key_down #

on_key_down: EventHandler[KeyDownEvent] | None = None

Fires when a keyboard key is pressed.

on_key_repeat #

on_key_repeat: EventHandler[KeyRepeatEvent] | None = None

Fires when a keyboard key is being hold, causing repeated events.

on_key_up #

on_key_up: EventHandler[KeyUpEvent] | None = None

Fires when a keyboard key is released.

focus #

focus()