Search code examples
pythonkivy

Python Kivy boxlayout unexpected behavior


I am trying to get a UI where the floatlayout takes up the top 80% of the screen, and a boxlayout takes out the bottom 20%. Intsead I get the floatlayout taking taking up the bottom 80%, with a empty space taking up the top 20%.

from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout

class UI(Screen):
    def __init__(self, **kwargs):
        super(UI, self).__init__(**kwargs)

        layout = BoxLayout(orientation='vertical')

        float_layout = FloatLayout()
        float_layout.size_hint_y = 0.8
        float_layout.add_widget(Button(text='Float Layout'))

        box_layout = BoxLayout()
        box_layout.size_hint_y = 0.2
        box_layout.add_widget(Button(text='Box Layout'))

        
        layout.add_widget(float_layout)
        layout.add_widget(box_layout)


        self.add_widget(layout)


class VNG(App):
    def build(self):
        return UI()

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

I tried using different positioning options but never got what I wanted. Flipping the order in which I add the layouts removes any black space, but it is inverted of what I want.


Solution

  • When you use a FloatLayout, you must position its children. The default position of any Widget is (0, 0), which is positioning your Button behind the BoxLayout. An easy fix is to use a RelativeLayout, which positions its children relative to it own position, so a (0, 0) position will be coincident with the RelativeLayout.