使用 Flet 在 Python 中创建待办事项应用 Create To-Do app in Python with Flet
翻译官网教程https://flet.dev/docs/tutorials/python-todo,对一些地方进行了注释和修改。
安装flet
Python版本需要3.8及以上,使用pip安装:
pip install flet
创建hello.py
,写入:
import flet as ft def main(page: ft.Page): page.add(ft.Text(value="Hello, world!")) ft.app(target=main)
运行该程序
python hello.py
看到一个写着Hello, world!
的窗口:
添加页面控件(controls)和处理事件
在页面上添加:
- 用来输入任务的文本框(TextField)
- 用于添加任务的按钮(FloatingActionButton)
import flet as ft def main(page: ft.Page): # 文本框,用来输入任务 new_task = ft.TextField(hint_text="Whats needs to be done?") def add_clicked(e): # 添加复选框, 刷新页面 page.add(ft.Checkbox(label=new_task.value)) new_task.value = "" page.update() # 添加任务的按钮 create_task_btn = ft.FloatingActionButton( icon=ft.icons.ADD, on_click=add_clicked # 绑定方法add_clicked ) page.add( new_task, create_task_btn, ) ft.app(target=main)
页面布局
我们希望调整页面布局,让任务文本框和添加按钮 在一行,
让创建出来的任务框在 下面。
使用Row按行放置其中的控件, Column按列放置其中的控件。
Row可以看成是一个容器,水平放置其中的组件。Row本身也是一个控件,因此可以嵌套使用。Column同理,用来竖直放置其中控件。
row_1 = ft.Row( width=600, controls=[new_task,create_task_btn] ) ... # Row可以嵌套。 view = ft.Column( width=600, controls=[row_1, tasks_view] )
完整代码:
import flet as ft def main(page: ft.Page): # 文本框,用来输入任务 new_task = ft.TextField(hint_text="Whats needs to be done?") # 保存复选框 tasks_view = ft.Column() def add_clicked(e): # 添加复选框, 刷新页面 tasks_view.controls.append(ft.Checkbox(label=new_task.value)) new_task.value = "" view.update() # 添加任务的按钮 create_task_btn = ft.FloatingActionButton( icon=ft.icons.ADD, on_click=add_clicked # 绑定方法add_clicked ) # 水平放置文本框和添加按钮 row_1 = ft.Row( width=600, controls=[new_task,create_task_btn] ) # 整个应用 view = ft.Column( width=600, controls=[row_1, tasks_view] ) page.horizontal_alignment = ft.CrossAxisAlignment.CENTER page.add(view) ft.app(target=main)
运行结果:
可重用的 UI 组件
为了制作一个可重用的 ToDo 应用组件,我们将将其状态和表示逻辑封装在一个单独的类中:
import flet as ft class TodoApp(ft.UserControl): def build(self): # 文本框,用来输入任务 self.new_task = ft.TextField(hint_text="Whats needs to be done?") # 任务 self.tasks = ft.Column() # 添加任务的按钮 create_task_btn = ft.FloatingActionButton( icon=ft.icons.ADD, on_click=self.add_clicked # 绑定方法add_clicked ) # 整个应用 self.view = ft.Column( width=600, controls=[ ft.Row( width=600, controls=[self.new_task,create_task_btn]), self.tasks] ) return self.view def add_clicked(self,e): # 添加任务, 刷新页面 self.tasks.controls.append(ft.Checkbox(label=self.new_task.value)) self.new_task.value = "" self.update() def main(page: ft.Page): page.title = "ToDo App" page.horizontal_alignment = ft.CrossAxisAlignment.CENTER page.update() todo = TodoApp() page.add(todo) ft.app(target=main)
用户控件 ( UserControl
) 允许通过组合现有的 Flet 控件来构建独立的可重用组件。UserControl
必须实现 build()
方法生成控件的 UI ,并且应返回单个 Control
实例或 List
控件。
查看、编辑和删除列表项
在任务名称旁边添加“编辑”和“删除"按钮。
任务的组成变得复杂起来了,我们创建一个Task
类来表示任务。
Task有两种模式,显示视图(display_view)和编辑视图(edit_view),通常情况下,我们看到的是显示视图,当点击编辑按钮时才会切换到编辑视图。可见性是通过设置它们的.visible
属性实现的。
class Task(ft.UserControl): def __init__(self, task_name,task_delete): super().__init__() self.task_name = task_name self.task_delete = task_delete def delete_clicked(self, e): self.task_delete(self) def build(self): self.display_task = ft.Checkbox(value=False, label=self.task_name) self.edit_name = ft.TextField(expand=1) self.display_view = ft.Row( alignment=ft.MainAxisAlignment.SPACE_BETWEEN, vertical_alignment=ft.CrossAxisAlignment.CENTER, controls=[ self.display_task, ft.Row( spacing=0, controls=[ ft.IconButton( icon=ft.icons.CREATE_OUTLINED, tooltip="Edit To-Do", on_click=self.edit_clicked, ), ft.IconButton( ft.icons.DELETE_OUTLINE, tooltip="Delete To-Do", on_click=self.delete_clicked, ), ], ), ], ) self.edit_view = ft.Row( visible=False, alignment=ft.MainAxisAlignment.SPACE_BETWEEN, vertical_alignment=ft.CrossAxisAlignment.CENTER, controls=[ self.edit_name, ft.IconButton( icon=ft.icons.DONE_OUTLINE_OUTLINED, icon_color=ft.colors.GREEN, tooltip="Update To-Do", on_click=self.save_clicked, ), ], ) return ft.Column(controls=[self.display_view, self.edit_view]) def edit_clicked(self, e): self.edit_name.value = self.display_task.label self.display_view.visible = False self.edit_view.visible = True self.update() def save_clicked(self, e): self.display_task.label = self.edit_name.value self.display_view.visible = True self.edit_view.visible = False self.update()
然后在TodoAPP中使用Task替代之前的简单复选框:
class TodoApp(ft.UserControl): def build(self): # 文本框,用来输入任务 self.new_task = ft.TextField(hint_text="Whats needs to be done?") # 任务 self.tasks = ft.Column() # ... def add_clicked(self, e): # 添加任务, 刷新页面 task = Task(self.new_task.value, self.task_delete) # 注意self.task_delete是TodoAPP的方法,作为参数传递给Task self.tasks.controls.append(task) self.new_task.value = "" self.update() def task_delete(self, task): self.tasks.controls.remove(task) self.update()
注意到Task
的delete_clicked
调用了self.task_delete
,而task_delete
是在TodoAPP.add_clicked
中作为初始化参数传递给Task的。
筛选列表项
我们希望能够按任务状态筛选任务。
我们使用Tabs
控件来显示多个选项卡,用不同的选项卡来显示不同状态的任务。
# ... class TodoApp(ft.UserControl): def __init__(self): self.tasks = [] self.new_task = ft.TextField(hint_text="Whats needs to be done?", expand=True) self.tasks = ft.Column() # 3个选项卡,作为过滤器 self.filter = ft.Tabs( selected_index=0, on_change=self.tabs_changed, tabs=[ft.Tab(text="all"), ft.Tab(text="active"), ft.Tab(text="completed")], ) self.view = ft.Column( width=600, controls=[ ft.Row( controls=[ self.new_task, ft.FloatingActionButton(icon=ft.icons.ADD, on_click=self.add_clicked), ], ), ft.Column( spacing=25, controls=[ self.filter, self.tasks, ], ), ], )
我们可以维护三个页面,分别显示“全部”、“活动”和“已完成”任务。但我们可以用更简单的方式,只维护一个页面,根据选择的选项卡更改任务的可见性。
def update(self): status = self.filter.tabs[self.filter.selected_index].text for task in self.tasks.controls: task.visible = ( status == "all" or (status == "active" and task.completed == False) or (status == "completed" and task.completed) ) super().update()
当我们单击选项卡或更改任务状态时,应该进行过滤。
class TodoApp(ft.UserControl): # ... def tabs_changed(self, e): self.update() class Task(ft.UserControl): def __init__(self, task_name, task_status_change, task_delete): super().__init__() self.completed = False # 任务是否完成 self.task_name = task_name self.task_status_change = task_status_change self.task_delete = task_delete def build(self): # 改变任务状态 self.display_task = ft.Checkbox( value=False, label=self.task_name, on_change=self.status_changed ) # ... def status_changed(self, e): self.completed = self.display_task.value self.task_status_change(self)
最后的润色
最后,我们将添加一个页脚,显示未完成任务的数量,以及一个“清除已完成”按钮。
class TodoApp(): def __init__(self): # ... self.items_left = ft.Text("0 items left") self.view = ft.Column( width=600, controls=[ ft.Row([ ft.Text(value="Todos", style="headlineMedium")], alignment=ft.MainAxisAlignment.CENTER), ft.Row( controls=[ self.new_task, ft.FloatingActionButton(icon=ft.icons.ADD, on_click=self.add_clicked), ], ), ft.Column( spacing=25, controls=[ self.filter, self.tasks, ft.Row( alignment=ft.MainAxisAlignment.SPACE_BETWEEN, vertical_alignment=ft.CrossAxisAlignment.CENTER, controls=[ self.items_left, ft.OutlinedButton( text="Clear completed", on_click=self.clear_clicked ), ], ), ], ), ], ) # ... def clear_clicked(self, e): # 注意这里 [:] 用的是一个copy来遍历,因为下面可能会进行删除操作 for task in self.tasks.controls[:]: if task.completed: self.task_delete(task) def update(self): status = self.filter.tabs[self.filter.selected_index].text count = 0 for task in self.tasks.controls: task.visible = ( status == "all" or (status == "active" and task.completed == False) or (status == "completed" and task.completed) ) if not task.completed: count += 1 self.items_left.value = f"{count} active item(s) left" super().update()
完整代码:
import flet as ft # 任务, 可以 完成、编辑、删除 class Task(ft.UserControl): def __init__(self, task_name,task_status_change,task_delete): super().__init__() self.completed = False self.task_name = task_name self.task_status_change = task_status_change self.task_delete = task_delete def build(self): self.display_task = ft.Checkbox(value=False, label=self.task_name, on_change=self.status_changed) self.edit_name = ft.TextField(expand=1) # 显示 self.display_view = ft.Row( alignment=ft.MainAxisAlignment.SPACE_BETWEEN, vertical_alignment=ft.CrossAxisAlignment.CENTER, controls=[ self.display_task, ft.Row( spacing=0, controls=[ ft.IconButton( icon=ft.icons.CREATE_OUTLINED, tooltip="Edit To-Do", on_click=self.edit_clicked, ), ft.IconButton( ft.icons.DELETE_OUTLINE, tooltip="Delete To-Do", on_click=self.delete_clicked, ), ], ), ], ) # 编辑 self.edit_view = ft.Row( visible=False, alignment=ft.MainAxisAlignment.SPACE_BETWEEN, vertical_alignment=ft.CrossAxisAlignment.CENTER, controls=[ self.edit_name, ft.IconButton( icon=ft.icons.DONE_OUTLINE_OUTLINED, icon_color=ft.colors.GREEN, tooltip="Update To-Do", on_click=self.save_clicked, ), ], ) return ft.Column(controls=[self.display_view, self.edit_view]) def delete_clicked(self, e): self.task_delete(self) def edit_clicked(self, e): self.edit_name.value = self.display_task.label self.display_view.visible = False self.edit_view.visible = True self.update() def save_clicked(self, e): self.display_task.label = self.edit_name.value self.display_view.visible = True self.edit_view.visible = False self.update() def status_changed(self, e): self.completed = self.display_task.value self.task_status_change(self) # 完整的todo界面。 class TodoApp(ft.UserControl): def build(self): # 文本框,用来输入任务 self.new_task = ft.TextField(hint_text="Whats needs to be done?") # 任务 self.tasks = ft.Column() # 过滤器。通过切换选项卡过滤不同状态的任务 self.filter = ft.Tabs( selected_index=0, on_change=self.tabs_changed, tabs=[ft.Tab(text="all"), ft.Tab(text="active"), ft.Tab(text="completed")], ) # 添加任务的按钮 create_task_btn = ft.FloatingActionButton( icon=ft.icons.ADD, on_click=self.add_clicked # 绑定方法add_clicked ) # 页脚,显示剩余任务 self.items_left = ft.Text("0 items left") # 整个应用 self.view = ft.Column( width=600, controls=[ ft.Row([ ft.Text(value="Todos", style="headlineMedium")], alignment=ft.MainAxisAlignment.CENTER), ft.Row( controls=[ self.new_task, create_task_btn] ), ft.Column( spacing=25, controls=[ self.filter, self.tasks, ft.Row( alignment=ft.MainAxisAlignment.SPACE_BETWEEN, vertical_alignment=ft.CrossAxisAlignment.CENTER, controls=[ self.items_left, ft.OutlinedButton( text="Clear completed", on_click=self.clear_clicked ), ], ), ], ), ], ) return self.view def add_clicked(self,e): # 添加任务, 刷新页面 task = Task(self.new_task.value, self.task_status_change, self.task_delete) self.tasks.controls.append(task) self.new_task.value = "" self.update() def tabs_changed(self, e): self.update() def task_delete(self, task): self.tasks.controls.remove(task) self.update() def task_status_change(self, task): self.update() def clear_clicked(self, e): for task in self.tasks.controls[:]: if task.completed: self.task_delete(task) def update(self): status = self.filter.tabs[self.filter.selected_index].text count = 0 for task in self.tasks.controls: task.visible = ( status == "all" or (status == "active" and task.completed == False) or (status == "completed" and task.completed) ) if not task.completed: count += 1 self.items_left.value = f"{count} active item(s) left" super().update() def main(page: ft.Page): page.title = "ToDo App" page.horizontal_alignment = ft.CrossAxisAlignment.CENTER page.update() todo = TodoApp() page.add(todo) ft.app(target=main)