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()
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()
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:
Example without on_size:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With