How to create a large number of buttons (+50) on a container and get the text of the one which was pressed

Hi, I need to create a lot of buttons inside of container, each button labeled with each item of a list. for example: list_of_names=[‘A’,‘B’,‘C’…‘Z’] and respectivly the buttons: (A)(B)(C)…(Z)

finally I need to display the text of the button that was just pressed. for example if I press the (Z) button I want to asign the text ‘Z’ to a Title at te top of my form for example to a self.label_1.text.

I’ve tryed:

list_of_names=[‘A’,‘B’,‘C’,…,‘Z’]

def xy_panel_1_show(self, **event_args):
for r in list_of_names:
self.xy_panel_1.add_component(Button(text=r))

with this code I de get the buttons with the names displayed on each button but… how could I get the text of the button that I press while running the app and asign that text to the label self.label_1.text ?

I dot want to create more than 50 buttons manually and asign the function
def self.button_1_click(), def self.button_2_click()… cause i need a lot of buttons.

Thanks!

You can assign multiple buttons to the same click function, so you can have your 50 buttons and only have one self.button_click() function tied to the click event for all the buttons.

Inside that function, the event_args parameter contains information about the event. event_args[‘sender’] has a reference to the button that generated the event.

1 Like

It’s still not clear to me how to make this assignment:

Could yo please write the solution you have in mind following the example I wrote above?

Remember I have created all 50 buttons with a for loop not manually. So there are none of the events: def self.button_1_click(): … def.self.button_50_click() wrote on my code.

Here is an example:

class Form1(Form1Template):
    def __init__(self, **properties):
        self.init_components(**properties)

        for n in range(50):
            button = Button(text=f'Button {n + 1}')
            self.add_component(button)
            button.add_event_handler('click', self.button_click)

    def button_click(self, **event_args):
        button = event_args['sender']
        print(button.text)

Here is the documentation: Anvil Docs | Anvil Components

4 Likes

Perfect! My code is working now!! Thanks :grin: