Search code examples
pythonflutterflet

FLET: Matematical operation on value in Slider controls


I have specific problem and i don't understand how to solve it :/

Source: FLET Slider Example

import flet as ft

def main(page):

    def slider_changed(e):
        t.value = f"Slider changed to {e.control.value}"
        page.update()

    t = ft.Text()
    page.add(
        ft.Text("Slider with 'on_change' event:"),
        ft.Slider(min=0, max=100, divisions=10, label="{value}%", on_change=slider_changed), t)

ft.app(main)

Value label works fine, but in my project I need to apply mathematical operation (dividing) on this value.

Value label="{value}%" is probably string, but when I try to transform it to int, debugger show me error ValueError: invalid literal for int() with base 10

Please, how can I divide value and after that show is as label?


Solution

  • import flet as ft
    
    def main(page):
        def slider_changed(e):
            #Store value to perform mathematical opreations on first
            slider_value = e.control.value
            # then divide slider value by an integer
            result = slider_value / 10
            #update both text and slider conntrol with result
            t.value = f"Slider value divided by 10 = {result}"
            my_slider.label = f"{result}%"
            page.update()
    
        t = ft.Text()
        my_slider = ft.Slider(min=0, max=100, divisions=10, label="{value}%", 
        on_change=slider_changed)
    
        page.add(
            ft.Text("Slider with 'on_change' event:"),
            my_slider, t)
        #print(my_slider.label)
    
    ft.app(main)
    

    From the Flet Slider documentation:

    "label: Format with {value}. A label to show above the slider when the slider is active. The value of label may contain {value} which will be replaced with a current slider value. It is used to display the value of a discrete slider, and it is displayed as part of the value indicator shape. If not set, then the value indicator will not be displayed."

    This implies that the label only serves as a display for the slider values. You cannot type cast it to an integer like you wanted to. A good way to achieve what you want is to perform the mathematical operation on the slider value directly and update it to any flet control, in your case the Text and Slider label. This way any changes to the slider gets updated. I hope this solves your issue?