Flet Introduction

It is a framework for building interactive multi-user web, desktop, and mobile applications in Python. It is not necessary to have prior experience with web technologies .

We can build a UI(User Interface) for a program using Flet controls, which are based on Google Flutter.

Installation

pip install flet

Hello World example using flet

import flet
from flet import Page, Text

def main(page: Page):
    page.add(Text("Hello, world!"))

flet.app(target=main)

Output

Example : Displaying a string “Python World”

import flet as ft

def main(page: ft.Page):
    t = ft.Text(value="Python World", color="green")
    page.controls.append(t)
    page.update()

ft.app(target=main)

Output

Here, page is the root control, or the top-most control. User interface is made of controls. Control must be added to the page or contained within another control in order for the user to see it. Nesting controls could be viewed as a tree, with Page as the root.

In order to display a control on a page, add it to the controls list of the page and call it using the page.update() to send changes to a browser or desktop client.

In the above code,, we have used a single string, “Python World” to display the message on the console. The same string can be broken into two parts and displayed on a separate line with a different color.

import flet as ft

def main(page: ft.Page):
    firststr = ft.Text(value="Python", color="green")
    secondstr = ft.Text(value="World", color="red")
    page.controls.append(firststr)
    page.controls.append(secondstr)
    page.update()

ft.app(target=main)

Now we will change the position of the strings. The first string to display is “World” and the second is “Python.”

import flet as ft

def main(page: ft.Page):
    firststr = ft.Text(value="Python", color="green")
    secondstr = ft.Text(value="World", color="red")
    page.controls.append(secondstr)
    page.controls.append(firststr)
    page.update()

ft.app(target=main)

Using page.add() to add controls to a page. It’s a quick way to use page.controls.append() and page.update(). 

import flet as ft

def main(page: ft.Page):
    firststr = ft.Text(value="Python", color="green")
    secondstr = ft.Text(value="World", color="red")
    page.add(firststr)
    page.add(secondstr)

ft.app(target=main)
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s