get pressed button value

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By mikbauer

How can I get value from a pressed button that was created in a loop.

I created 3 buttons:

func genButtons():
	for i in 3:
		buttons.append(Button.new())
		buttons[i].text = str(modText[MOD][i])
		add_child(buttons[i])

But I am not sure how to figure out which button I pressed?

:bust_in_silhouette: Reply From: jgodfrey

You’ll want to wire a pressed event to each button, and then pass the button reference through the callback. From there, you can directly access the pressed button’s data, including it’s text property (assuming that’s what you mean by value). Untested (and adding to your code above), but something like:

func genButtons():
    for i in 3:
        var button = Button.new()
        buttons.append(button)
        button.text = str(modText[MOD][i])
        add_child(button)
        button.connect("pressed", self, "_button_pressed", [button])

func _button_pressed(button):
	print(button.text)

So other may benefit from my question. This one worked for me

func genButtons():
    for i in 3:
        buttons.append(Button.new())
        buttons[i].text = str(modText[MOD][i])
        add_child(buttons[i])
        buttons[i].connect("pressed", self, "_button_pressed", [buttons[i]])

func _button_pressed(button):
    print(button.text)

mikbauer | 2023-01-12 21:36