Skip to content

Clipboard

Provides access to the system clipboard.

Inherits: Service

Methods

  • get

    Retrieves data from the clipboard.

  • get_files

    Retrieves file references from the clipboard.

  • get_image

    Retrieves image data from the clipboard.

  • set

    Stores the given data on the clipboard.

  • set_files

    Stores file references on the clipboard.

  • set_image

    Stores image bytes on the clipboard.

Examples#

Text#

import flet as ft


async def main(page: ft.Page):
    async def set_to_clipboard():
        await ft.Clipboard().set(text_to_copy.value)
        text_to_copy.value = ""
        page.show_dialog(ft.SnackBar("Text copied to clipboard"))

    async def get_from_clipboard():
        contents = await ft.Clipboard().get()
        page.add(ft.Text(f"Clipboard contents: {contents}"))

    page.add(
        ft.Column(
            controls=[
                text_to_copy := ft.TextField(label="Text to copy"),
                ft.Button("Set to clipboard", on_click=set_to_clipboard),
                ft.Button("Get from clipboard", on_click=get_from_clipboard),
            ],
        )
    )


ft.run(main)

Images#

import base64

import flet as ft

SAMPLE_PNG = base64.b64decode(
    "iVBORw0KGgoAAAANSUhEUgAAABkAAAAgCAYAAADnnNMGAAAACXBIWXMAAAORAAADkQFnq8zdAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAA6dJREFUSImllltoHFUYx3/fzOzm0lt23ZrQ1AQbtBehNpvQohgkBYVo410RwQctNE3Sh0IfiiBoIAjqi6TYrKnFy4O3oiiRavDJFi3mXomIBmOxNZe63ay52GR3Zj4f2sTEzmx3m//TYf7/c35zvgPnO6KqrESXqpq3muocAikv6m+/zytj3ejik1VN21G31YA9CgJ6xC+bMyQZPVCuarciPAMYC99V6Vw5pLbFSibHmlVoRVj9P3cmPBM8tSJI/M6mzabpfoAQ9fIF7WK4bd5vvuFnLGgy2vi0abg94A0AcJGvMq3hDxGRyar9r4F+iLAm0yIiRk8m37tctS1WsrIhhrI30+Srmg+J87OXUf3lWGS1q89dC6ltsSanxk4Aj2QBABii96300g87P/rtlrWr8l+vyDMfdlXSyyEikqxsiOUAQJCBhfHdXRfCq1LSsSlcWG+KBAGStvvrMkgiuv8lUc2mREukPwLUfHG+uTQv8Eown7VL3XlbBxYhf1c17hbVF3MDwA9bts280TnaU1YYqPby07aeFlUlHt27wSQ4CLo+F8AvoTCvHmyKF+ZbEb/M77P2LgvAwmrTHAHflN3KZxVbMC2jMFNOpgPnrMSOhvvFkMezXdwV4ePbtvHtxnJAMQ0j4JtVnO+eLb5oiSlt5HDbv7t1O90lpYCCCKbhfzW5kAIwUAazR0BlfII8Ow0I6uoVmI9MyAMwbMs8CExmDbk4zgu931MyO4OI4KrYflkRjOoTI+uM9d1vjotwKPu9QMk/sxzuO8POiVFcdZ1M2YBVsMEAKOqLvaPIe7mACuw0z/80SMH58SMplxlfiDhVi7dw2pltRhjKBQTQdrSja2KKTfE551NHuaZ0QVPvWYQUn31/Vm2nDvgjF4grVJx6suSvrvrSJ/6cSW2Oz9mf264uNrB806xZ1k/CZ49dUKgDEtlCROX2hfHpx8pGuuo3PpqYulw8fjndOp1yhgtNKRevJ1FyR2Ola+jXAjdnwTkZ6o896GdWdxDw7IxFg+0DpmXchTKSBWQnIuJn9u4j7dt+13UfHXEkXQOcuQ4kMhVtqsgUyPiQiPQfHw1NB2sRjmXKuTg1NwwBYLhtPtQX26eqTwGXPDOqvmcC4Hnwfrrad94GrVsOYTqUTkQY+iTlNe/6O1miSP/x0VB/+wMIDwHn/vtV1iQC4Xv95uUEWVCoL9Y5Z+gdovoyMHUFJHv88jmVy0vTuw7cZNv2YaA61Bfb7ZX5F8SaUv2xwZevAAAAAElFTkSuQmCC"
)


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

    async def set_image_to_clipboard(e: ft.Event[ft.Button]):
        await ft.Clipboard().set_image(SAMPLE_PNG)
        status.value = f"Sample image copied to clipboard ({len(SAMPLE_PNG)} bytes)."
        preview.content = ft.Image(src=SAMPLE_PNG)

    async def get_image_from_clipboard(e: ft.Event[ft.Button]):
        clipboard_image = await ft.Clipboard().get_image()
        if clipboard_image is None:
            status.value = "No image found in clipboard."
            preview.content = None
            return
        else:
            preview.content = ft.Image(src=clipboard_image)
            status.value = (
                f"Image loaded from clipboard ({len(clipboard_image)} bytes)."
            )

    page.add(
        ft.SafeArea(
            ft.Column(
                horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                controls=[
                    ft.Button(
                        "Set example image to clipboard",
                        on_click=set_image_to_clipboard,
                        disabled=not (page.web or page.platform.is_mobile()),
                        tooltip="Supported on mobile platforms only."
                        if not (page.web or page.platform.is_mobile())
                        else None,
                    ),
                    ft.Button(
                        "Get image from clipboard",
                        on_click=get_image_from_clipboard,
                    ),
                    status := ft.Text(),
                    preview := ft.Container(width=360, height=240),
                ],
            )
        )
    )


ft.run(main)

Files#

import os
import subprocess
import sys
import tempfile
from pathlib import Path

import flet as ft


def open_file(path: str):
    """Open a desktop file in the default application."""
    if os.path.isfile(path):
        if sys.platform == "darwin":  # macOS
            subprocess.run(["open", path])
        elif sys.platform == "win32":  # Windows
            os.startfile(path)
        else:  # Linux / BSD
            subprocess.run(["xdg-open", path])


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

    # supported-platform checkers
    supports_set_files = not page.web and page.platform.is_desktop()
    supports_get_files = not page.web and (
        page.platform.is_desktop() or page.platform == ft.PagePlatform.ANDROID
    )

    def get_sample_files() -> list[str]:
        # create temporary files
        sample_dir = Path(tempfile.gettempdir()) / "flet_clipboard_files_example"
        sample_dir.mkdir(parents=True, exist_ok=True)
        sample_files = [
            sample_dir / "sample_1.txt",
            sample_dir / "sample_2.txt",
        ]
        sample_files[0].write_text("Clipboard sample file #1\n", encoding="utf-8")
        sample_files[1].write_text("Clipboard sample file #2\n", encoding="utf-8")
        return [str(p) for p in sample_files]

    async def set_files_to_clipboard(e: ft.Event[ft.Button]):
        files = get_sample_files()
        ok = await ft.Clipboard().set_files(files)
        status.value = (
            f"Set {len(files)} file references to clipboard (result: {ok})."
            if ok
            else "Failed to set file references to clipboard."
        )

    async def get_files_from_clipboard(e: ft.Event[ft.Button]):
        files = await ft.Clipboard().get_files()
        if files:
            files_lv.controls = [
                ft.Row(
                    alignment=ft.MainAxisAlignment.CENTER,
                    controls=[
                        ft.Text(f, selectable=True),
                        ft.IconButton(
                            icon=ft.Icons.OPEN_IN_NEW,
                            icon_size=15,
                            on_click=lambda f=f: open_file(f),
                            tooltip="Open file",
                        ),
                    ],
                )
                for f in files
            ]
        else:
            files_lv.controls = []
        status.value = f"Read {len(files)} file reference(s) from clipboard."

    page.add(
        ft.SafeArea(
            ft.Column(
                horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                controls=[
                    ft.Button(
                        "Set example files to clipboard",
                        on_click=set_files_to_clipboard,
                        disabled=not supports_set_files,
                        tooltip="Supported on desktop platforms only."
                        if not supports_set_files
                        else None,
                    ),
                    ft.Button(
                        "Get files from clipboard",
                        on_click=get_files_from_clipboard,
                        disabled=not supports_get_files,
                        tooltip="Supported on Android and desktop platforms only."
                        if not supports_get_files
                        else None,
                    ),
                    status := ft.Text(),
                    files_lv := ft.Column(
                        horizontal_alignment=ft.CrossAxisAlignment.CENTER,
                        spacing=0,
                        controls=[],
                    ),
                ],
            )
        )
    )


ft.run(main)

Methods#

get async #

get() -> Optional[str]

Retrieves data from the clipboard.

Returns:

  • Optional[str]

    The string data retrieved from the clipboard, or None if the clipboard is empty or does not contain string data.

get_files async #

get_files() -> list[str]

Retrieves file references from the clipboard.

Returns:

  • list[str]

    A list of file references available in the clipboard.

  • list[str]

    On Android these are typically content URIs.

Raises:

get_image async #

get_image() -> Optional[bytes]

Retrieves image data from the clipboard.

Returns:

  • Optional[bytes]

    The image data retrieved from the clipboard as bytes, or None if the clipboard is empty or does not contain image data.

set async #

set(value: str) -> None

Stores the given data on the clipboard.

Parameters:

  • value (str) –

    The string data to be stored on the clipboard.

set_files async #

set_files(files: list[str]) -> bool

Stores file references on the clipboard.

Parameters:

  • files (list[str]) –

    A list of file paths.

Returns:

  • bool

    True if the operation succeeded, otherwise False.

Raises:

set_image async #

set_image(value: bytes) -> None

Stores image bytes on the clipboard.

Parameters:

  • value (bytes) –

    The image data (in bytes) to be stored on the clipboard.

Raises: