Creating a button through code ?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By benbaz4
:warning: Old Version Published before Godot 3 was released.

Hi guys,
I know this question may sound silly, but I am an unexperienced programmer.
I am trying to code something that should create and show a button over a Panel.
Here is what i’ve tried :

extends Panel

func _ready():
	OS.set_window_size(Vector2(800,600))
	set_size(OS.get_window_size())
	var button1 = Button.new()
	button1.set_pos(Vector2(20,20))
	button1.set_size(Vector2(80,20))
   	button1.show()
	pass

But it doesn’t work and I don’t even see the button1 variable in the debugger tab.
Do you know what I’ve done wrong ?
Sorry if this is stupid and thanks for your help.

:bust_in_silhouette: Reply From: atze

You forgot to add the button to the scene tree

...

func _ready():
    ...
    add_child(button1)
    pass

'… 'is a placeholder for the code you already wrote in your question

:bust_in_silhouette: Reply From: genete

Everything in the node hierarchy has to be child of a node. Try to insert add_child(button1) once button1 is prepared before show it. Possibly show() is not needed.

:bust_in_silhouette: Reply From: benbaz4

It worked !
Thanks again for your help, it’s very appreciated.