Search code examples
pythonlabelkivytext-alignment

Python Kivy: Align text to the left side of a Label


I read the docs, and still don't know how to align the text inside a Kivy-Label to its left side. The text is centered from default. A halign = "left" didn't help. Sorry, if the solution is obvious, but I simply don't find it.

EDIT: Example code:

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label

class Example(App):
     def build(self):
          self.root = FloatLayout()
          self.label = Label(text="I'm centered :(", pos=(0,0), size_hint=(1.0,1.0), halign="left")
          self.label.text_size = self.label.size #no horizontal change
          self.root.add_widget(self.label)
          return self.root

Example().run()

Solution

  • According to the documentation, it appears that the new created label have a size which exactly fit the text length so you might not see any differences after setting the halign property.

    It is recommended there to change the size property (as shown in the example)

    text_size = self.size
    

    which will set the size of the label to the widget containing it. Then you should see that the label is correctly centered.

    As Tshirtman pointed out, you also have to bind text_size property to size. Full working example:

    #!/usr/bin/kivy
    # -*- coding: utf-8 -*-
    
    from kivy.app import App
    from kivy.uix.floatlayout import FloatLayout
    from kivy.uix.label import Label
    
    class Example(App):
        def build(self):
            self.root = FloatLayout()
            self.label = Label(text="I'm aligned :)", size_hint=(1.0, 1.0), halign="left", valign="middle")
            self.label.bind(size=self.label.setter('text_size'))    
            self.root.add_widget(self.label)
            return self.root
    
    Example().run()