How to make buttons feed input into a function?

Rather than calling a function that takes in no prior inputs, I am trying to set up buttons so that based on which button is selected, that button feeds input into a function and calls that function

What I’ve tried and what’s not working:

Code Sample:

buttons = [Button(text="button-1", bold=True).set_event_handler("click", self.test("button_1_input"), 
               Button(text="button-2", bold=True).set_event_handler("click", self.test("button_2_input") ``` 

Clone link:
share a copy of your app

Welcome to the forum!

You might want to give more details about what you’re trying to accomplish, as opposed to a detailed technical question. The Anvil tutorials cover handling the click event on a button, so I’m assuming you’re trying to accomplish something more than just that. The context around what you’re trying to do helps people offer better advice.

Here’s a description of how to ask a question in a way that’s designed to get useful feedback: How to ask a good question

For what it’s worth, your code sample has a number of issues, but I wouldn’t even attempt to offer any fixes without knowing the context.

I realized in my original post, I accidentally had set the component to be a Label, instead of a Button. I have fixed that. I understand that my code snippet is wrong, which is why I am posting this question.

Let me try and explain my problem in further detail. From the guides on anvil, it would be easy for me to give each button its own function. The following is the function that would be called when the button is clicked.

def button1_click(self, **event_args):
    input = "button1_input"
    self.main_function(input)

I want to avoid creating this intermediary function, and immediately call the main_function with the appropriate input based on which button is clicked. The sample code I attached is how I tried to reach that conclusion.

1 Like

You can give each button the same click function. One of the event_args parameters is sender, which is the component that generated the event. So you could use event_args['sender'].text to get the text of the button that generated the event.

The event_args elements are documented in the section on component events: Anvil Docs | Anvil Components

2 Likes