Search code examples
pythonkivyboxlayout

python3 kivy BoxLayout over another


I looked at the documentation to know how to place my Box Layout in my kivy window

https://kivy.org/docs/api-kivy.uix.boxlayout.html

but i want to place my BoxLayout over another (with transparent background) like this :

enter image description here

my code (without my five transparent red box)

from kivy.app import App

from kivy.uix.boxlayout import BoxLayout

from kivy.uix.button import Button



# Boxlayout is the App class

class BoxLayoutDemo(App):

    def build(self):

        superBox        = BoxLayout(orientation='vertical')



        horizontalBox   = BoxLayout(orientation='horizontal')

        button1         = Button(text="One")

        button2         = Button(text="Two")



        horizontalBox.add_widget(button1)

        horizontalBox.add_widget(button2)



        verticalBox     = BoxLayout(orientation='vertical')

        button3         = Button(text="Three")

        button4         = Button(text="Four")



        verticalBox.add_widget(button3)

        verticalBox.add_widget(button4)



        superBox.add_widget(horizontalBox)

        superBox.add_widget(verticalBox)



        return superBox





# Instantiate and run the kivy app

if __name__ == '__main__':

    BoxLayoutDemo().run()

Solution

  • Use a FloatLayout as your root widget, and pos_hint: {'top': 1} so that you can place the transparent BoxLayout at the top. As for transparency, use Button's background_normal and background_color.

    Snippets

    FloatLayout:
    ...
        # topBox
        BoxLayout:
            Button:
                text: 'Five (with transparent red background)'
                background_normal: ''
                background_color: 0.8, 0, 0, 0.5  # 5% red
                size_hint: (0.5, 0.1)
                pos_hint: {'top': 1}
    

    Example

    main.py

    from kivy.lang import Builder
    from kivy.base import runTouchApp
    
    runTouchApp(Builder.load_string('''
    FloatLayout:
        size: (300, 300)
    
        # superBox
        BoxLayout:
            orientation: 'vertical'
    
            # horizontalBox
            BoxLayout:
                # orientation: 'horizontal' - default orientation is horizontal
                Button:
                    text: 'One'
                Button:
                    text: 'Two'
    
            # verticalBox
            BoxLayout:
                orientation: 'vertical'
                Button:
                    text: 'Three'
                Button:
                    text: 'Four'
    
        # topBox
        BoxLayout:
            Button:
                text: 'Five (with transparent red background)'
                background_normal: ''
                background_color: 0.8, 0, 0, 0.5  # 5% red
                size_hint: (0.5, 0.1)
                pos_hint: {'top': 1}
    
    '''))
    

    Output

    Img01