当前位置: 首页> 文旅> 美景 > python nicegui实现TodoList应用案例

python nicegui实现TodoList应用案例

时间:2025/7/16 20:00:53来源:https://blog.csdn.net/weixin_42357472/article/details/140907135 浏览次数:0次

参考:
https://nicegui.io/
https://nicegui.io/#demos

版本

nicegui                        1.4.30

代码:

python todolist.py

from nicegui import ui
from typing import List
import jsonclass Todo:def __init__(self, text: str, completed: bool = False):self.text = textself.completed = completedclass TodoList:def __init__(self):self.todos: List[Todo] = []self.load_todos()def add_todo(self, text: str):self.todos.insert(0, Todo(text))self.save_todos()def remove_todo(self, todo: Todo):self.todos.remove(todo)self.save_todos()def toggle_todo(self, todo: Todo):todo.completed = not todo.completedself.todos.sort(key=lambda t: t.completed)self.save_todos()def load_todos(self):try:with open('todos.json', 'r') as f:data = json.load(f)self.todos = [Todo(**item) for item in data]except FileNotFoundError:self.todos = []def save_todos(self):with open('todos.json', 'w') as f:json.dump([todo.__dict__ for todo in self.todos], f)todo_list = TodoList()@ui.page('/')
def todo_page():ui.add_head_html('''<style>body {font-family: Arial, sans-serif;max-width: 500px;margin: 0 auto;padding: 20px;}.todo-item {display: flex;align-items: center;padding: 10px;background-color: #f9f9f9;border: 1px solid #ddd;margin-bottom: 10px;border-radius: 4px;}.todo-item.completed {text-decoration: line-through;opacity: 0.6;}.delete-button {margin-left: auto;background-color: #f44336;color: white;border: none;padding: 5px 10px;border-radius: 4px;cursor: pointer;}</style>''')ui.label('TodoList').style('font-size: 24px; text-align: center;')todo_container = ui.column()def update_todos():todo_container.clear()for todo in todo_list.todos:with todo_container:with ui.row().classes('todo-item' + (' completed' if todo.completed else '')):ui.checkbox(value=todo.completed, on_change=lambda e, t=todo: todo_list.toggle_todo(t) or update_todos())ui.label(todo.text)ui.button('Delete', on_click=lambda e, t=todo: todo_list.remove_todo(t) or update_todos()).classes('delete-button')def add_todo():if todo_input.value:todo_list.add_todo(todo_input.value)todo_input.value = ''update_todos()with ui.row().classes('todo-form'):todo_input = ui.input(placeholder='Enter a new todo').classes('todo-input')ui.button('Add', on_click=add_todo).classes('add-button')update_todos()ui.run()

网页打开查看:
在这里插入图片描述

关键字:python nicegui实现TodoList应用案例

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: