3

I want to align the text of the button to the left with halign='left' in Kivy, but it does not work and keeps it centered.

This is my code:

import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty

class MyGrid(GridLayout):
    def __init__(self, **kwargs):
        super(MyGrid, self).__init__(**kwargs)
        self.cols = 1

        for i in range (0,10):
            self.btn = Button(text=str(i),halign='left',background_color =(.3, .6, .7, 1))
            self.btn.bind(on_press=self.pressed)
            self.add_widget(self.btn)


    def pressed(self, instance):
        print ("Name:",instance.text)



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


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

1 Answers1

1

According to the documentation for halign:

This doesn’t change the position of the text texture of the Label (centered), only the position of the text in this texture. You probably want to bind the size of the Label to the texture_size or set a text_size.

So, to get the result you want, you can define an extension to Button that does what the above documentation suggests:

class MyButt(Button):
    pass

Builder.load_string('''
<MyButt>:
    halign: 'left'
    text_size: self.size
    background_color: (.3, .6, .7, 1)
''')

Then use that class in your App:

class MyGrid(GridLayout):
    def __init__(self, **kwargs):
        super(MyGrid, self).__init__(**kwargs)
        self.cols = 1

        for i in range (0,10):
            self.btn = MyButt(text=str(i))
            self.btn.bind(on_press=self.pressed)
            self.add_widget(self.btn)
John Anderson
  • 35,991
  • 4
  • 13
  • 36