大家好,今天为大家分享一个非常好用的 Python 库 - nicegui。
Github地址:https://github.com/zauberzeug/nicegui
nicegui是一个Python库,为开发者提供了一种极其简便的方式来构建现代化Web用户界面。与传统Web开发不同,使用NiceGUI无需编写HTML、CSS或JavaScript代码,开发者只需使用熟悉的Python语法即可创建响应式、美观的Web应用。NiceGUI基于FastAPI和Socket.IO构建,具备高性能和实时通信能力,同时保持极简的API设计理念。=
安装
1、基本安装方法 NiceGUI可以通过Python的包管理器pip轻松安装:
pip install nicegui
对于希望使用最新功能的开发者,可以从GitHub安装:
pip install git+https://github.com/zauberzeug/nicegui.git
2、验证安装 安装完成后,可以通过导入库并启动一个简单的应用来验证安装是否成功:
from nicegui import ui ui.label( 'Hello, NiceGUI!' ) ui.run()
如果成功运行,浏览器将会打开并显示"Hello, NiceGUI!"文本。
特性 纯Python开发 :无需HTML、CSS或JavaScript知识 丰富的组件 :预置大量UI组件,从基础控件到复杂图表 易于集成 :可与现有Flask、FastAPI应用集成
语义化版本控制 :稳定的API,遵循SemVer规范 基本功能 1、创建基础UI元素 NiceGUI提供了丰富的基础UI元素,包括按钮、标签、输入框等。以下示例展示如何创建一个简单的表单,这些基础元素是构建复杂界面的基础,适用于创建各类交互式应用。
from nicegui import ui def show_message () : ui.notify( f'Hello, {name.value} !' ) with ui.card().classes( 'w-80' ): ui.label( 'User Registration' ).classes( 'text-xl font-bold' ) name = ui.input( 'Name' ) email = ui.input( 'Email' ).props( 'type=email' ) password = ui.input( 'Password' ).props( 'type=password' ) ui.button( 'Register' , on_click=show_message) ui.run()
2、响应式布局 NiceGUI支持响应式布局,使应用能够自适应不同屏幕尺寸。以下示例展示如何使用行和列创建适应性布局,这对于开发跨设备应用非常重要,可确保在手机、平板和桌面设备上都有良好的用户体验。
from nicegui import ui with ui.row(): with ui.card().classes( 'w-1/3' ): ui.label( 'Card 1' ) ui.button( 'Click me!' ) with ui.card().classes( 'w-1/3' ): ui.label( 'Card 2' ) ui.switch( 'Toggle me' )
with ui.card().classes( 'w-1/3' ): ui.label( 'Card 3' ) ui.checkbox( 'Check me' ) ui.run()
3、事件处理 事件处理是交互式应用的核心,NiceGUI提供了简洁的方式来注册和响应用户操作。以下示例展示如何创建一个简单的计数器应用,展示了事件处理的基本用法,适用于需要对用户输入作出响应的各类应用。
from nicegui import ui counter = 0 def increment () : global counter counter += 1 label.set_text( f'Count: {counter} ' ) def reset () : global counter counter = 0 label.set_text( f'Count: {counter} ' ) label = ui.label( f'Count: {counter} ' ) with ui.row(): ui.button( 'Increment' , on_click=increment) ui.button( 'Reset' , on_click=reset).props( 'outline' ) ui.run()
高级功能 1、数据可视化 NiceGUI集成了多种数据可视化组件,使创建交互式图表变得简单。以下示例展示如何创建折线图和饼图,这对于数据分析和监控应用尤为重要,可直观展示数据趋势和分布。
from nicegui import ui import numpy as np # 创建折线图 with ui.card().classes( 'w-full' ): x = np.linspace( 0 , 10 , 100 ) y = np.sin(x) ui.line_plot(x=x, y=y).classes( 'h-40' ) # 创建饼图 with ui.card().classes( 'w-full' ): labels = [ 'A' , 'B' , 'C' , 'D' ] values = [ 15 , 30 , 25 , 30 ] ui.pie_plot(labels=labels, values=values).classes( 'h-40' ) ui.run()
2、页面路由 NiceGUI支持页面路由,使开发多页面应用变得简单。以下示例展示如何创建具有不同页面的应用,这对于构建复杂的Web应用至关重要,允许开发者组织内容并提供清晰的导航结构。
from nicegui import ui @ui.page('/') def home () : ui.label( 'Home Page' ).classes( 'text-2xl font-bold' ) ui.label( 'Welcome to my NiceGUI application' ) ui.link( 'Go to About' , '/about' ) @ui.page('/about') def about () : ui.label( 'About Page' ).classes( 'text-2xl font-bold' ) ui.label( 'This is a simple multi-page app built with NiceGUI' ) ui.link( 'Go to Home' , '/' ) ui.run()
3、文件上传和下载 NiceGUI简化了文件上传和下载操作,使处理用户文件变得直观。以下示例展示如何创建文件上传组件并处理上传的文件,这对于需要文件交互的应用非常实用,如文档管理系统或数据分析工具。
from nicegui import ui import pandas as pd import io def handle_upload (e) : try : content = e.content.read() df = pd.read_csv(io.BytesIO(content)) ui.notify( f'Successfully loaded CSV with {len(df)} rows' ) # 显示数据预览 with results_container: ui.html( 'Data Preview: ' ) ui.html(df.head().to_html()) except Exception as ex: ui.notify( f'Error: {str(ex)} ' , color= 'negative' ) ui.upload(on_upload=handle_upload, label= 'Upload CSV file' , multiple= False , accept= '.csv' ) results_container = ui.element( 'div' ) ui.run()
实际应用场景
实时物联网监控面板 以下是使用NiceGUI创建物联网设备监控面板的示例。这种应用场景常见于工业自动化、智能家居和远程设备管理,通过NiceGUI可以快速开发直观的监控界面。
from nicegui import ui import random import asyncio # 模拟传感器数据 temperature = 21.0 humidity = 45.0 # 创建UI元素 with ui.card().classes( 'w-full max-w-3xl mx-auto' ): ui.label( 'IoT Device Dashboard' ).classes( 'text-2xl font-bold' ) with ui.row(): with ui.card().classes( 'w-1/2' ): ui.label( 'Temperature' ).classes( 'text-lg' ) temp_label = ui.label( f' {temperature} °C' ).classes( 'text-2xl' ) temp_plot = ui.line_plot(x=[], y=[]).classes( 'h-40' ) with ui.card().classes( 'w-1/2' ): ui.label( 'Humidity' ).classes( 'text-lg' ) humid_label = ui.label( f' {humidity} %' ).classes( 'text-2xl' ) humid_plot = ui.line_plot(x=[], y=[]).classes( 'h-40' ) with ui.row(): status = ui.label( 'Status: Connected' ).classes( 'text-green-500' ) ui.button( 'Refresh' , on_click= lambda : ui.notify( 'Refreshed!' )) # 模拟数据更新 temp_data = [] humid_data = [] time_points = [] current_time = 0
async def update_sensors () : global temperature, humidity, current_time while True : # 模拟数据变化 temperature += random.uniform( -0.5 , 0.5 ) humidity += random.uniform( -1 , 1 ) # 更新UI temp_label.set_text( f' {temperature: .1 f} °C' ) humid_label.set_text( f' {humidity: .1 f} %' ) # 更新图表 current_time += 1 time_points.append(current_time) temp_data.append(temperature) humid_data.append(humidity) # 保持图表数据点数量为50 if len(time_points) > 50 : time_points.pop( 0 ) temp_data.pop( 0 ) humid_data.pop( 0 ) temp_plot.update(x=time_points, y=temp_data) humid_plot.update(x=time_points, y=humid_data) await asyncio.sleep( 1 ) ui.timer( 1.0 , lambda : asyncio.create_task(update_sensors()), once= True ) ui.run()
总结 Python NiceGUI库是一个突破性的框架,它简化了Web用户界面的开发过程,使Python开发者无需前端开发经验即可创建美观、响应式的Web应用。通过纯Python代码构建界面的方式消除了传统Web开发的复杂性,同时保持了现代Web应用的功能和外观。NiceGUI适用于广泛的应用场景,从简单的控制面板到复杂的数据可视化工具,都能快速高效地实现。