0

I am using Flet module to create a simple GUI.

I want to access the custom data on the button. However, using the clicked method, it seems that the event handler of the button using the data property of it, returns empty string. Therefore, the method does not print anything.

Using flet 0.1.62, Python 3.10

import flet
from flet import UserControl, TextButton, Row, Page


class Test(UserControl):
    def __init__(self):
        super().__init__()

        self.text_button = TextButton(text='test', data='test', on_click=self.clicked)
        self.view = Row(controls=[self.text_button])

    def clicked(self, e):
        print(e.data, ' was clicked')

    def build(self):
        return self.view


def main(page: Page):
    t = Test()
    page.add(t)


app = flet.app(target=main)

It seems in the flet's tutorials for the Calculor example, that you can have multiple buttons using the same method for on_click argument.

this is a part from the example's code where it refers to Handling events: https://flet.dev/docs/tutorials/python-calculator/

Now let's make the calculator do its job. We will be using the same event handler for all the buttons and use data property to differentiate between the actions depending on the button clicked. For each ElevatedButton control, specify on_click=self.button_clicked event and set data property equal to button's text, for example:

ft.ElevatedButton(
    text="AC",
    bgcolor=ft.colors.BLUE_GREY_100,
    color=ft.colors.BLACK,
    expand=1,
    on_click=self.button_clicked,
    data="AC",
)

Below is on_click event handler that will reset the Text value when "AC" button is clicked:

def button_clicked(self, e):
    if e.data == "AC":
        self.result.value = "0"

With similar approach, specify on_click event and data property for each button and add expected action to the button_clicked event handler depending on e.data value.

I am looking for a way to get the same result using the TextButton, I'd appreciate your help!

ted
  • 13,596
  • 9
  • 65
  • 107
Javid
  • 21
  • 4

1 Answers1

2

I found the answer to my own question. Apparently in the version of the flet that I am using, the data property has to be looked up through the control instance attribute. Therefore I tried this in the code from my question:

def clicked(self, e):
        print(e.control.data, ' was clicked')

instead of:

def clicked(self, e):
        print(e.data, ' was clicked')

I tried it out of curiosity and it worked.

Javid
  • 21
  • 4