{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 事件\n", "\n", "您可以注册协程或函数,以便在以下事件发生时被调用:\n", "\n", "- `app.on_startup`:在 NiceGUI 启动或重启时调用\n", "- `app.on_shutdown`:在 NiceGUI 关闭或重启时调用\n", "- `app.on_connect`:每个连接的客户端都会调用(可选参数:`nicegui.Client`)\n", "- `app.on_disconnect`:每个断开连接的客户端都会调用(可选参数:`nicegui.Client`)\n", "- `app.on_exception`:发生异常时调用(可选参数:`exception`)\n", "\n", "当 NiceGUI 关闭或重启时,所有仍在执行的任务将自动取消。" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from datetime import datetime\n", "from nicegui import app, ui\n", "\n", "dt = datetime.now()\n", "\n", "def handle_connection():\n", " global dt\n", " dt = datetime.now()\n", "app.on_connect(handle_connection)\n", "\n", "label = ui.label()\n", "ui.timer(1, lambda: label.set_text(f'Last new connection: {dt:%H:%M:%S}'))\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 }