How to change Button color via GDScript

Hi, I was searching for how to change a button color without having to use TextureButton, but I didn’t find anything useful. Now that I have figured it out, I want to make a post to solve this kind of doubt for others searching for something similar.

I attributed a StyleBoxFlat to the Button node via the editor. The function below extracts the style of this node and changes the background_color and border_color to the Color passed, then reapplies this newly altered style.

func _ready():
	set_stylebox_color("normal", Color.GREEN)
func set_stylebox_color(style_box_type: String, color: Color):
	var stylebox_theme: StyleBoxFlat = $Button.get_theme_stylebox(style_box_type)
	stylebox_theme.bg_color = color
	stylebox_theme.border_color = color
	$Button.add_theme_stylebox_override(style_box_type, stylebox_theme)

This code retrieves the StyleBoxFlat from the node, either from the default/custom theme or the style assigned in the theme override via the editor, specific to the type you are changing. I did this to replicate other changes I made in the editor, but you can create a new style instead of editing the node’s existing style.

Yes, you can use var style_box =

1 Like