{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 计时器\n", "\n", "创建 NiceGUI 的主要动力之一是需要一个简单方法来定期更新界面,例如显示带有传入测量值的图表。计时器将使用给定的时间间隔重复执行回调函数。\n", "\n", "- `interval`:调用计时器的间隔(可以在运行时更改)\n", "- `callback`:当时间间隔过去时要执行的函数或协程\n", "- `active`:是否应执行回调函数(可以在运行时更改)\n", "- `once`:是否仅在间隔指定的延迟后执行一次回调(默认:`False`)" ] }, { "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 ui\n", "\n", "label = ui.label()\n", "ui.timer(1.0, lambda: label.set_text(f'{datetime.now():%X}'))\n", "\n", "# ui.run()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 激活、停用和取消计时器\n", "\n", "您可以使用 `active` 属性来激活和停用计时器。您可以使用 `cancel` 方法来取消计时器。取消计时器后,它将无法再次激活。" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from nicegui import ui\n", "\n", "slider = ui.slider(min=0, max=1, value=0.5)\n", "timer = ui.timer(0.1, lambda: slider.set_value((slider.value + 0.01) % 1.0))\n", "ui.switch('active').bind_value_to(timer, 'active')\n", "ui.button('Cancel', on_click=timer.cancel)\n", "\n", "# ui.run()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 在延迟后调用函数\n", "\n", "您可以使用带有 `once` 参数的计时器在延迟后调用函数。" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from nicegui import ui\n", "\n", "def handle_click():\n", " ui.timer(1.0, lambda: ui.notify('Hi!'), once=True)\n", "ui.button('Notify after 1 second', on_click=handle_click)\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 }