Flet Tutorial

What is Flet? 

Flet is a set of bindings which allow Python programmers access to Flutter, the most used Mobile UI library. Flet also allows users to create website, desktop and mobile interfaces all while using Python. With a wide variety of unique features such as Hot Reload Support, Backend Integration and a sleek modern GUI look, Flet is quickly becoming one of the most popular Python GUI libraries. 

Why use Flet? 

Flet is a highly versatile Python GUI library which is popular because it allows users to: 

  • Create cross-platform apps for Windows, Linux, macOS as well as iOS and Android
  • Design websites while still coding in Python
  • Offer fast and real-time updates on apps thanks to its adaptability for both apps and websites
  • Utilize a modern and highly customizable GUI library
  • Harness Flutter’s powerful library without the difficulty of Dart code
  • Easily create Python backend with specialized functions and features 

While Flet has a long list of pros and benefits it is also noticeably more difficult to learn and code in then compared with other Python GUI libraries such as Tkinter, this is important to note as while Flet has a much more customizable and modern look, it also has a steeper learning curve. 

Flet Button Click Event 

This example creates a simple button that, when clicked, calls a function and prints a message to the console. It’s a basic but essential interaction pattern in Flet, demonstrating how GUI elements like buttons are linked to backend logic via event callbacks.

import flet as ft  # Import Flet module for GUI creation 

# Function that will be called when the button is clicked
def on_click(e):
    print("Button was clicked!")  # Print a message to the console 

def main(page: ft.Page):
    page.title = "Button Click Event"  # Set window title
    # Create an ElevatedButton widget and add it to the page
    page.add(ft.ElevatedButton(text="Click Me", on_click=on_click)) 

ft.app(target=main)  # Start the Flet application 

Flet Entry to Label Update 

In this example, users can type text into a TextField, and when they press the button, the entered text appears in a Text widget. This demonstrates how to retrieve input from widgets, dynamically update other elements, and create interactive UIs.

import flet as ft  # Import Flet module 

def main(page: ft.Page):
    # Create TextField widget for user input
    entry = ft.TextField(label="Enter text")
    # Create a Text widget to display output
    label = ft.Text("Waiting for input...") 

    # Function to update label with text from entry
    def update(e):
        label.value = entry.value  # Get text from entry and set it as label text
        page.update()  # Refresh UI 

    # Create ElevatedButton that triggers update() when clicked
    page.add(entry, ft.ElevatedButton(text="Submit", on_click=update), label) 

ft.app(target=main)  # Start the GUI loop

Flet Calculator with Event Handling 

This example builds a mini calculator interface using a grid of buttons and a TextField for displaying expressions. It uses Python’s eval() function to evaluate mathematical input and handles basic arithmetic. It also demonstrates binding multiple buttons to the same logic with slight variation. 

import flet as ft  # Import Flet 

def main(page: ft.Page):
    page.title = "Simple Calculator"  # Set window title 

    # Expression string to hold user input
    expr = ""
    expr_display = ft.TextField(value="", text_align="right", font_size=16, width=240, read_only=True) 

    # Function to append characters to the expression
    def press(e):
        nonlocal expr
        expr += e.control.data
        expr_display.value = expr
        page.update() 

    # Function to evaluate the expression
    def calculate(e):
        nonlocal expr
        try:
            expr = str(eval(expr))  # Evaluate the expression
        except:
            expr = "Error"
        expr_display.value = expr
        page.update() 

    # Function to clear the expression
    def clear(e):
        nonlocal expr
        expr = ""
        expr_display.value = expr
        page.update() 

    # Display and button layout
    page.add(expr_display)
    buttons = [
        "7", "8", "9", "/",
        "4", "5", "6", "*",
        "1", "2", "3", "-",
        "0", ".", "=", "+"
    ]
    for i, char in enumerate(buttons):
        action = calculate if char == "=" else press
        page.add(ft.ElevatedButton(text=char, data=char, width=60, height=40, on_click=action))
    page.add(ft.ElevatedButton(text="C", width=240, on_click=clear)) 

ft.app(target=main)  # Run the application

Flet Table with DataTable 

This example uses Flet’s DataTable widget to display tabular data (like a spreadsheet). It includes column headers, aligns text, and is ideal for displaying structured datasets such as CSV files, user lists, or scores. 

import flet as ft  # Import Flet 

def main(page: ft.Page):
    page.title = "Data Table Example"  # Set window title 

    # Define DataTable with columns and sample row data
    data_table = ft.DataTable(
        columns=[
            ft.DataColumn(label=ft.Text("ID")),
            ft.DataColumn(label=ft.Text("Name")),
            ft.DataColumn(label=ft.Text("Score")),
        ],
        rows=[
            ft.DataRow(cells=[ft.DataCell(ft.Text("1")), ft.DataCell(ft.Text("Alice")), ft.DataCell(ft.Text("90"))]),
            ft.DataRow(cells=[ft.DataCell(ft.Text("2")), ft.DataCell(ft.Text("Bob")), ft.DataCell(ft.Text("85"))]),
        ]
    ) 

    page.add(data_table)  # Display table 

ft.app(target=main)  # Start the GUI loop

Flet Canvas Drawing Shapes 

This code introduces a Stack widget, which allows you to draw 2D shapes by layering Containers. Can be used for custom drawings, charts, or basic games. The example demonstrates positioning and layering of graphical elements. 

import flet as ft  # Import Flet 

def main(page: ft.Page):
    page.title = "Canvas Drawing"  # Set window title 

    # Create a Stack to mimic a canvas
    stack = ft.Stack(width=300, height=200, bgcolor=ft.colors.WHITE) 

    # Draw a rectangle
    stack.controls.append(
        ft.Positioned(
            left=50, top=50,
            width=200, height=100,
            child=ft.Container(border=ft.border.all(2, ft.colors.BLACK))
        )
    )
    # Draw an oval by using border radius
    stack.controls.append(
        ft.Positioned(
            left=70, top=60,
            width=160, height=80,
            child=ft.Container(bgcolor=ft.colors.SKYBLUE, border_radius=ft.border_radius.all(40))
        )
    )
    # Add centered text
    stack.controls.append(
        ft.Positioned(
            left=150, top=90,
            child=ft.Text("Canvas Example", size=12)
        )
    ) 

    page.add(stack)  # Add drawing area 

ft.app(target=main)  # Run the application

Flet AppBar with Commands 

This example demonstrates how to create an AppBar with Help and Exit commands. Each item is linked to a specific command, such as exiting the app or showing an info dialog. AppBars are essential for creating professional, user-friendly applications. 

import flet as ft  # Import Flet 

def main(page: ft.Page):
    # Function to show About message
    def show_about(e):
        dlg = ft.AlertDialog(
            title=ft.Text("About"),
            content=ft.Text("This is a Flet menu example."),
            actions=[ft.TextButton("OK", on_click=lambda e: dlg.close())]
        )
        page.dialog = dlg
        dlg.open = True
        page.update() 

    # Create AppBar with actions
    page.appbar = ft.AppBar(
        title=ft.Text("Menu Example"),
        actions=[
            ft.IconButton(icon=ft.icons.HELP, tooltip="About", on_click=show_about),
            ft.IconButton(icon=ft.icons.EXIT_TO_APP, tooltip="Exit", on_click=lambda e: page.window_close())
        ]
    )
    page.add(ft.Text("Content goes here"))  # Main content 

ft.app(target=main)  # Start the GUI loop 

Flet File Picker Example 

This code allows users to open a file picker to select a text file. Once selected, the file’s contents are loaded into a Text widget. This is particularly useful for file editors, configuration loaders, or file-based input interfaces. 

import flet as ft  # Import Flet 

def main(page: ft.Page):
    # Function to open file picker
    def open_file(e):
        file_picker.pick_files(allow_multiple=False, dialog_title="Select a text file", file_type=ft.FilePicker.TFileType.CUSTOM, file_type_filter=[".txt"]) 

    # Callback when file is selected
    def on_file_result(e: ft.FilePickerResultEvent):
        if e.files:
            path = e.files[0].path
            with open(path, "r") as f:
                text.value = f.read()
            page.update() 

    # Setup FilePicker control
    file_picker = ft.FilePicker(on_result=on_file_result)
    page.overlay.append(file_picker) 

    # UI: Button to trigger file picker and Text to display contents
    text = ft.Text()
    page.add(ft.ElevatedButton(text="Open File", on_click=open_file), text) 

ft.app(target=main)  # Run the application 

Flet Progress Bar (Indeterminate)

This example adds a progress bar in indeterminate mode, where it shows ongoing processing. It also includes Start and Stop buttons to control the bar. It’s commonly used when you don’t know the task duration, such as loading data or checking for updates. 

import flet as ft  # Import Flet 

def main(page: ft.Page):
    page.title = "Progress Bar Example"  # Set window title
    # Create an indeterminate progress bar (value=None)
    pb = ft.ProgressBar(width=200, value=None) 

    # Start progress
    def start(e):
        pb.value = 0.5  # Simulate progress
        page.update() 

    # Stop/reset progress
    def stop(e):
        pb.value = 0
        page.update() 

    page.add(pb, ft.Row([ft.ElevatedButton(text="Start", on_click=start), ft.ElevatedButton(text="Stop", on_click=stop)])) 

ft.app(target=main)  # Start the GUI loop

Flet Notebook (Tabbed UI)

This example uses Flet’s Tabs control to create a tabbed interface. Each tab contains different content, making it easier to organize complex applications like settings panels, dashboards, or multi-step wizards. 

import flet as ft  # Import Flet 

def main(page: ft.Page):
    page.title = "Tabbed Interface Example"  # Set window title 

    # Create tabs with content in separate containers
    tab1 = ft.Container(content=ft.Text("This is the Home tab."), padding=20)
    tab2 = ft.Container(content=ft.Text("Settings go here."), padding=20)
    tab3 = ft.Container(content=ft.Text("About information."), padding=20) 

    tabs = ft.Tabs(
        selected_index=0,
        tabs=[
            ft.Tab(text="Home", content=tab1),
            ft.Tab(text="Settings", content=tab2),
            ft.Tab(text="About", content=tab3),
        ]
    ) 

    page.add(tabs)  # Add to page 

ft.app(target=main)  # Run the application 

Flet GUI Designer 

With our drag and drop Flet GUI Designer, you can save all the hassle of slowly writing hundreds of lines of Flet code and let you focus on the actual looks and functionality of your apps. Adjustments can be made in a few seconds; events handling is centralized and easy to understand. Our Flet GUI Designer allows you to quickly make GUIs without a fuss. We can see it at work below. 

GUI made with Flet GUI Designer

This simple example took a few minutes to be made, and adjustments can be made even faster. While with traditional coding, this simple example would take much longer and adjustments would be slower, limiting your designs and missing your deadlines.