Search code examples
pythonlayoutraspberry-pikivykivy-language

How to set a label position to border in Kivy?


Hi i have problems with positioning of my labels in Kivy. I think pictures can describe my problem best.

How it looks like now... How it looks like now...

How I want it looks like... How I want it looks like...

I want to bind the Label 3 to the right border. I have no Idea how to do this. My Code:

import kivy

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

from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

root = Builder.load_string('''
Screen:
    BoxLayout:
        orientation:'vertical'
        Label:
            text: '1'
            font_size: self.height
            size_hint: (1.0, 0.17)
        Label:
            text: '2'
            font_size: self.height
            size_hint: (1.0, 0.83)
    Label:
        text: '3'
''')

class MyApp(App):
    def build(self):
        root.size_hint = (1.0, 1.0)
        return root

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

Solution

  • For this type of cases there is AnchorLayout, which serves to align the widgets to a relative position.

    import kivy
    
    from kivy.app import App
    from kivy.uix.label import Label
    
    from kivy.uix.boxlayout import BoxLayout
    from kivy.lang import Builder
    
    root = Builder.load_string('''
    Screen:
        BoxLayout:
            orientation:'vertical'
            Label:
                text: '1'
                font_size: self.height
                size_hint: (1.0, 0.17)
            Label:
                text: '2'
                font_size: self.height
                size_hint: (1.0, 0.83)
    
        AnchorLayout:
            anchor_x: 'right'
            anchor_y: 'bottom'
            Label:
                text: '3'
                font_size: self.height
                size_hint: None, None
    ''')
    
    class MyApp(App):
        def build(self):
            root.size_hint = (1.0, 1.0)
            return root
    
    if __name__ == '__main__':
        MyApp().run()
    

    enter image description here