python-3.xfor-loopflet

How to change the color to a specific button, added to Flet's page using a for loop in a Python3 script?


I have a simple Python3 script, where i add 5 green Flet-buttons using a for loop:

import flet as fl
def main(page:fl.Page):
    def change_color(e):
        # what for changing color to specific button?
        print('color changed')
    column=fl.Column(controls=[fl.ElevatedButton(n,color='green',on_click=change_color) for n in range(5)])
    page.add(column)
fl.app(target=main)

I would like to change to red the color of the button I just clicked


Solution

  • I finally got it:

    import flet as fl
    def main(page:fl.Page):
        def change_color(e):
            e.control.color='red'
            e.control.update()
        column=fl.Column(controls=[fl.ElevatedButton(n,color='green',on_click=change_color) for n in range(5)])
        page.add(column)
    fl.app(target=main)