pythonflet

How to pass value from function to ft.Text (framework FLET)?


I want to create a simple stopwatch in Python using the Flet, how can I get my value out of the while loop?

import flet as ft
from time import sleep

def stopwatch():
    time = 0
    str_time = ''
    while True:
        time += 1
        str_time = str(time)
        print(str_time, time) #for check work or not
        sleep(1)


def main(page: ft.Page):
    t = ft.Text(value=stopwatch(), color='red') #no value is transmitted
    page.controls.append(t)
    page.update()

ft.app(target=main)

I tried to use return and the value 1 was passed, but the while loop stopped there. Possibly I don't know much Python and especially the Flet, but I managed to write such a simple program using TKinter, I want to repeat the same success with Flet)


Solution

  • There is an example of a countdown timer in the flet reference. This is a custom text control. To run it in the background, you use page.run_task() to execute a method that implements the logic. This example has been changed to a stopwatch specification.

    import asyncio
    import flet as ft
    
    class Stopwatch(ft.Text):
        def __init__(self, seconds):
            super().__init__()
            self.seconds = seconds
    
        def did_mount(self):
            self.running = True
            self.page.run_task(self.update_timer)
    
        def will_unmount(self):
            self.running = False
    
        async def update_timer(self):
            while self.seconds >= 0 and self.running:
                mins, secs = divmod(self.seconds, 60)
                self.value = "{:02d}:{:02d}".format(mins, secs)
                self.update()
                await asyncio.sleep(1)
                self.seconds += 1
    
    def main(page: ft.Page):
        page.add(Stopwatch(0))
    
    ft.app(main)