Search code examples
buttoninputtextlabelgodot

Godot: tap button to write text in label


I built a 0-9 number-pad from several Buttons and placed a Label above. What I'd like is to click on a number and have it written in the label.

I managed to have the dedicated text appear directly on the button with this code:

extends Button

onready var supertext = get_tree().get_root().find_node("TheOneLabel")

func _ready():
    set_process_input(true)

func _on_Button_gui_input(event):
    if event.is_action_pressed("mousebuttonclick"):
        print ("clicked!)
    elif event.is_action_released("mousebuttonclick"):
        _the_wonders_of_button_1()

func _the_wonders_of_button_1():
    set_text("That's a 1!")

But I couldn't make it into TheOneLabel yet, although I have the strong feeling that the var supertext might come in handy... can anyone tell me how I can connect my Buttons to the Label? (Tapping buttons in a row should create a row of numbers then. And is a Label actually useful to further use its text or should I maybe use some different text-node in the first place?)


Solution

  • You should control the label with the parent of the label or just the root node. Under the "node" tab, then the "signals" tab in the button inspector, connect the "pressed()" signal to the function you want that changes the label text in the parent script. Then just put $Label.text = "Hello" in that function. Another option would be to connect the signal to a function you can call in the label script as well.