Skip to content

示例 ​

python
import flet as ft


def main(page: ft.Page):
    page.horizontal_alignment = ft.CrossAxisAlignment.CENTER

    messages = ft.Column(tight=True)

    def handle_dialog_dismissal(_: ft.Event[ft.DialogControl]):
        messages.controls.append(ft.Text("Dialog dismissed"))

    def handle_action_click(e: ft.Event[ft.CupertinoDialogAction]):
        messages.controls.append(ft.Text(f"Action clicked: {e.control.content}"))
        page.pop_dialog()

    cupertino_alert_dialog = ft.CupertinoAlertDialog(
        title=ft.Text("Cupertino Alert Dialog"),
        content=ft.Text("Do you want to delete this file?"),
        on_dismiss=handle_dialog_dismissal,
        actions=[
            ft.CupertinoDialogAction(
                destructive=True,
                on_click=handle_action_click,
                content="Yes",
            ),
            ft.CupertinoDialogAction(
                default=True,
                on_click=handle_action_click,
                content="No",
            ),
        ],
    )

    page.add(
        ft.SafeArea(
            content=ft.Column(
                horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                controls=[
                    ft.CupertinoFilledButton(
                        on_click=lambda _: page.show_dialog(cupertino_alert_dialog),
                        content="Open CupertinoAlertDialog",
                    ),
                    messages,
                ],
            ),
        )
    )


if __name__ == "__main__":
    ft.run(main)
file-deletion-confirmation
python
from typing import Union

import flet as ft


def main(page: ft.Page):
    page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
    page.scroll = ft.ScrollMode.AUTO

    messages = ft.Column(tight=True)

    def handle_action_click(
        e: ft.Event[Union[ft.TextButton, ft.CupertinoDialogAction]],
    ):
        messages.controls.append(ft.Text(f"Action clicked: {e.control.content}"))
        page.pop_dialog()

    cupertino_actions = [
        ft.CupertinoDialogAction(
            destructive=True,
            on_click=handle_action_click,
            content="Yes",
        ),
        ft.CupertinoDialogAction(
            default=False,
            on_click=handle_action_click,
            content="No",
        ),
    ]

    material_actions = [
        ft.TextButton(on_click=handle_action_click, content="Yes"),
        ft.TextButton(on_click=handle_action_click, content="No"),
    ]

    page.add(
        ft.SafeArea(
            content=ft.Column(
                horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                controls=[
                    ft.FilledButton(
                        on_click=lambda _: page.show_dialog(
                            ft.AlertDialog(
                                title=ft.Text("Material Alert Dialog"),
                                content=ft.Text("Do you want to delete this file?"),
                                actions=material_actions,
                            )
                        ),
                        content="Open Material Dialog",
                    ),
                    ft.CupertinoFilledButton(
                        on_click=lambda _: page.show_dialog(
                            ft.CupertinoAlertDialog(
                                title=ft.Text("Cupertino Alert Dialog"),
                                content=ft.Text("Do you want to delete this file?"),
                                actions=cupertino_actions,
                            )
                        ),
                        content="Open Cupertino Dialog",
                    ),
                    ft.FilledButton(
                        adaptive=True,
                        bgcolor=ft.Colors.BLUE_ACCENT,
                        on_click=lambda _: page.show_dialog(
                            ft.AlertDialog(
                                adaptive=True,
                                title=ft.Text("Adaptive Alert Dialog"),
                                content=ft.Text("Do you want to delete this file?"),
                                actions=(
                                    cupertino_actions
                                    if page.platform.is_apple()
                                    else material_actions
                                ),
                            )
                        ),
                        content="Open Adaptive Dialog",
                    ),
                    messages,
                ],
            ),
        )
    )


if __name__ == "__main__":
    ft.run(main)

CupertinoDialogAction 继承自: Control, BaseControl

A dialog action button.

Typically used as a child of actions.

属性 ​

名称类型默认值说明
contentAnnotated[StrOrControl, V.str_or_visible_control()]requiredThe content of this action button. Raises: ValueError: If it is neither a string nor a visible Control.
defaultboolFalseWhether this action is a default action. In this case, the button will have bold text. Info: Multiple actions can have this property set to True in a CupertinoAlertDialog.
destructiveboolFalseIf set to True, this button's text color will be red. Typically used for actions that destroy objects, such as an delete that deletes an email etc.
text_styleOptional[TextStyle]NoneThe text style to use for text in this button. Can be useful when content is a string.
expandAnnotated[Optional[Union[bool, int]], V.instance_of((bool, int))]None指定此控件是否/如何扩展以填充父布局中的可用空间。 详见 此处. Note: Has effect only if the direct parent of this control is one of the following controls, or their subclasses: Column, Row, View, Page. Raises: ValueError: If it is not of type bool or int.
expand_looseboolFalse允许控件在主轴方向上有可用空间时扩展,但不要求填满所有可用空间。 详见 此处. Note: 若 expand_loose 为 True,则仅当同时满足以下条件时生效: - expand 不为 None,且 - the direct parent of this control is one of the following controls, or their subclasses: Column, Row, View, Page.
colResponsiveNumber12若此控件的父控件是 ResponsiveRow,此属性用于决定该控件横跨多少个虚拟列。 可以是数字,也可以是为不同断点配置不同值的字典,例如 col={"sm": 6}。 0 表示在该断点下隐藏控件,不占用任何列。 默认横跨 12 个虚拟列。 \
opacityAnnotated[Number, V.between(0.0, 1.0)]1.0定义控件的透明度,取值范围 0.0(完全透明)到 1.0(完全不透明)。 抛出异常:ValueError:若不在 0.0 到 1.0 的闭区间内。
tooltipOptional[TooltipValue]None鼠标悬停时显示的 tooltip。
badgeOptional[BadgeValue]None显示在控件顶部的徽标。
visibleboolTrueEvery control has visible property which is True by default - control is rendered on the page. Setting visible to False 完全阻止该控件(及其所有子控件)渲染到页面画布上. 隐藏的控件不能通过键盘或鼠标聚焦或选中,也不会触发任何事件。
disabledboolFalseEvery control has disabled property which is False by default - control and all its children are enabled. Note: The value of this property will be propagated down to all children controls recursively. Example: For example, if you have a form with multiple entry controls you can disable them all together by disabling container: python ft.Column( disabled = True, controls=[ ft.TextField(), ft.TextField() ] )
rtlboolFalse控件的文字方向是否为从右到左(RTL)。
dataAnyskip_任意类型的自定义数据。
keyOptional['KeyValue']None用于在更新之间保持控件身份稳定的 key。

只读属性 ​

名称类型默认值说明
parentOptional['BaseControl']—The direct ancestor(parent) of this control. It defaults to None and will only have a value when this control is mounted (added to the page tree). Page 控件(树的根)为例外 —— 它始终 parent=None。
page'Page'—此控件所属的页面。

事件 ​

名称类型默认值说明
on_clickOptional[ControlEventHandler['CupertinoDialogAction']]NoneCalled when a user clicks this button.

方法 ​

名称类型默认值说明
is_isolated——Return whether this control is marked as isolated. 被隔离的控件不会参与父级驱动的更新遍历,需要自行管理更新边界。
init——Called after control instance initialization and before the first build / update cycle. 可重写此钩子执行依赖于已初始化字段的轻量设置。 不要在这里调用 update()。
build——在控件初始化期间调用一次,用于定义其子控件。 page 属性在此方法中可用。
before_update——每次控件即将更新时调用。 Note: 不要在此处调用 update()。
before_event——在事件处理器执行前拦截事件。 返回 False 取消分发,返回 True 或 None 则继续正常的事件处理。
did_mount——在控件挂载到页面树之后调用。 可重写以启动需要已挂载页面的资源,例如订阅、定时器或服务监听。
will_unmount——在控件从页面树移除之前调用。 可重写以释放 did_mount() 中创建的资源,例如订阅、定时器或外部句柄。
get_data_channel——Resolve the [DataChannel] allocated on the Dart side for this widget. Pattern: on_data_channel_open: Optional[ft.EventHandler[DataChannelOpenEvent]] = None def init(self): self.on_data_channel_open = self._on_open def _on_open(self, e): self._channel = self.get_data_channel(e.channel_id) Idempotent — the underlying Connection caches DataChannels by id, so repeated calls return the same instance. No error path: the id always comes from a framework-fired event, so by the time this runs the channel exists on both sides.
updateNone—请求更新该控件的 UI。 在修改控件状态或属性后调用。 控件必须已挂载到页面,并且未被冻结。

关注我,学习大模型、大数据、Python等热门技术。