Button text wont align center when i edit the text with a script

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

The text aligned fine when I put it in manually, but I want it to update passively with the script

Is your button’s text alignment set to center? Changing the text dynamically (via script) works fine for me here. The new string (regardless of length) stays centered in the button.

jgodfrey | 2023-03-29 15:51

I do have it set to center. Could you send your code for how you update the text?

turtilla955 | 2023-03-29 16:24

More importantly, you might want to show how you’re updating the text. I’m just assigning a new value to the button’s text property. So, this…

$Button.text = "My new button text"

jgodfrey | 2023-03-29 16:33

For a more dynamic example.

In a scene structured as follows:


Associate the following script to Node2D:

extends Node2D

func _on_button_2_pressed():
	var s = ["short", "even longer 123", "an even longer string to test", "medium xxx"]
	$Button.text = s.pick_random()

Connect Button2’s pressed signal to the above event handler. That’ll assign one of the array strings to the Button.text each time Button2 is pressed.

Again, works as expected here.

jgodfrey | 2023-03-29 16:44

I do the same thing. One of my updates is

$button.text = str("text " + str(var) + "text")

turtilla955 | 2023-03-29 17:41

Does my above example work correctly for you? You can easily just set up a temporary scene in your project to test it…

jgodfrey | 2023-03-29 18:06

Unrelated, but your above code can be simplified to this:

$button.text = "text %stext" % v

Here, in my testing, the string produced by your code above is centered in a sample button (as expected).

jgodfrey | 2023-03-29 18:20

I have discovered the actual problem. It centers the text correctly but when the text
Is bigger then the button it startes stretching it to the right which made me think it was not getting centered. I should be able just make the button larger to fix the problem, thanks for the help

turtilla955 | 2023-03-29 18:56