Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 478
d0n.key Avatar asked Jul 26 '15 15:07

d0n.key


2 Answers

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()
like image 80
rebrec Avatar answered Oct 10 '22 22:10

rebrec


I'm kind of late to the party, but another nice trick I found for this is if you create your labels using your own custom class, you can define in that class the on_size function to change the text_size to size.

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label  
          
class MyLabel(Label):
   def on_size(self, *args):
      self.text_size = self.size
    
class Example(App):
           def build(self):
              self.root = FloatLayout()
              self.label = MyLabel(text="I'm aligned :)", size_hint=(1.0, 1.0), halign="left", valign="middle")
              self.root.add_widget(self.label)
              return self.root
    
Example().run()

Example with on_size:

enter image description here

Example without on_size:

without on_size

like image 30
Jonathan. Avatar answered Oct 10 '22 23:10

Jonathan.