[파이썬] Kivy `AnchorLayout` 배치

In this blog post, we will explore how to use the AnchorLayout in Kivy to create a responsive and flexible user interface.

Creating an AnchorLayout

To use the AnchorLayout in Kivy, you first need to import it from the kivy.uix.anchorlayout module. Then, create an instance of the AnchorLayout class.

from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.button import Button
from kivy.app import App

class AnchorLayoutApp(App):
    def build(self):
        layout = AnchorLayout()
        # Add widgets to the layout
        layout.add_widget(Button(text='Hello', size_hint=(None, None), size=(200, 100)))
        layout.add_widget(Button(text='World', size_hint=(None, None), size=(200, 100)))
        return layout

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

In the above example, we create an instance of the AnchorLayout class and add two Button widgets as its children. We set the size_hint property of the buttons to (None, None) to disable the automatic resizing, and set the size property to (200, 100) to define their initial size.

Positioning Widgets with Anchor Layout

The AnchorLayout positions its children using a set of anchors, which are points on the layout’s boundaries. By default, the AnchorLayout centers its children horizontally and vertically. However, you can anchor the children to any edge or corner of the layout.

from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.button import Button
from kivy.app import App

class AnchorLayoutApp(App):
    def build(self):
        layout = AnchorLayout()

        # Add widgets with different anchors
        layout.add_widget(Button(text='Top Left', size_hint=(None, None), size=(200, 100),
                                 **{'top': layout.top, 'left': layout.left}))
        layout.add_widget(Button(text='Bottom Right', size_hint=(None, None), size=(200, 100),
                                 **{'bottom': layout.bottom, 'right': layout.right}))

        return layout

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

In this example, we add two Button widgets to the AnchorLayout. The first button is anchored to the top-left corner of the layout, and the second button is anchored to the bottom-right corner. We achieve this by passing the appropriate values for the top, bottom, left, and right properties when adding the widgets.

Conclusion

The AnchorLayout in Kivy provides a simple yet powerful way to position widgets within a layout. By utilizing its anchors, you can easily create responsive user interfaces that adapt to different screen sizes and orientations.

In this blog post, we covered the basics of using the AnchorLayout and demonstrated how to position widgets using different anchors. I hope this tutorial helps you in your Kivy development journey!

Let me know if you have any questions or suggestions in the comments below. Happy coding!