参考:
https://nicegui.io/
https://nicegui.io/#demos
版本
nicegui 1.4.30
代码:
python todolist.py
from nicegui import ui
from typing import List
import json
class Todo:
def __init__(self, text: str, completed: bool = False):
self.text = text
self.completed = completed
class 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.completed
self.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()
网页打开查看: