{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 键盘\n", "\n", "添加全局键盘事件跟踪。\n", "\n", "- `on_key`:当键盘事件发生时执行的回调函数\n", "- `active`:指示是否应执行回调函数的布尔标志(默认:`True`)\n", "- `repeating`:指示是否应重复发送按住的键的布尔标志(默认:`True`)\n", "- `ignore`:当这些元素类型之一获得焦点时忽略按键(默认:`['input', 'select', 'button', 'textarea']`)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from nicegui import ui\n", "from nicegui.events import KeyEventArguments\n", "\n", "def handle_key(e: KeyEventArguments):\n", " if e.key == 'f' and not e.action.repeat:\n", " if e.action.keyup:\n", " ui.notify('f was just released')\n", " elif e.action.keydown:\n", " ui.notify('f was just pressed')\n", " if e.modifiers.shift and e.action.keydown:\n", " if e.key.arrow_left:\n", " ui.notify('going left')\n", " elif e.key.arrow_right:\n", " ui.notify('going right')\n", " elif e.key.arrow_up:\n", " ui.notify('going up')\n", " elif e.key.arrow_down:\n", " ui.notify('going down')\n", "\n", "keyboard = ui.keyboard(on_key=handle_key)\n", "ui.label('Key events can be caught globally by using the keyboard element.')\n", "ui.checkbox('Track key events').bind_value_to(keyboard, 'active')\n", "\n", "# ui.run()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "py311", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.7" } }, "nbformat": 4, "nbformat_minor": 2 }