1

What is the problem with this code? The last button that is created is always the one that is clicked!

import flet as ft

def main(page: ft.Page):

    def click(e, button: ft. Button):
        button.bgcolor = ft.Colors.YELLOW
        button.page.update()

    words = ['ma', 'ti', 'ke', 'to', 'pe', 'la', 'su']
    buttons = []
    
    for word in words:
        button = ft.Button(text=word)
        button.on_click = lambda e: click(e, button)
        buttons.append(button)

    page.add(ft.Row(buttons))

ft.app(main)

1 Answer 1

0

I found the answer. It was in the call for lambda function. It should be:

for word in words:
    button = ft.Button(text=word)
    button.on_click = lambda e, btn=button: click(e, btn)
    buttons. Append(button)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.