How to center text in kivy

Viewed 112

I am trying to center text in kivy. I tried using halign="center" like so:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import CoreLabel
from kivy.graphics import Rectangle, Color
from kivy.core.window import Window

class MyWidget(Widget):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        Window.clearcolor = (1, 1, 1, 1)
        self.canvas.clear()

        with self.canvas:
            Color(0, 0, 0, 1)

            label = CoreLabel(text="Text", font_size=50, halign="center")
            label.refresh()
            text = label.texture
            Rectangle(size=text.size, pos=(865, 30), texture=text)

class MyApp(App):
    def build(self):
        return MyWidget()

if __name__ == "__main__":
    MyApp().run()

But that doesn't center the text around the given position (it is still left aligned). If I change the length of the text (and therefore its size), its position doesn't change, even though I want it to.

1 Answers

Try adding

label = CoreLabel(halign='center',valign='center')
Related