[파이썬] Kivy `GridLayout` 배치

Kivy is an open-source Python framework for developing multi-touch applications. It provides a wide range of UI elements to create interactive and responsive user interfaces. One of the essential layout managers in Kivy is the GridLayout, which allows you to arrange widgets in a grid-like structure.

In this blog post, we will explore how to use the GridLayout in Kivy to arrange widgets in a grid pattern.

Setting Up the Environment

Before we dive into the GridLayout layout manager, make sure you have Kivy installed on your machine. You can install Kivy using pip:

pip install kivy

Creating a Simple GridLayout

To use the GridLayout, we first need to import the required modules from Kivy:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button

Next, we create a class that inherits from the GridLayout class:

class MyGridLayout(GridLayout):
    pass

The MyGridLayout class will serve as the container for the widgets that we want to arrange in a grid pattern.

Next, we define the layout of the MyGridLayout class by adding widgets to it:

class MyGridLayout(GridLayout):
    def __init__(self, **kwargs):
        super(MyGridLayout, self).__init__(**kwargs)
        
        # Specify the number of columns in the grid
        self.cols = 2
        
        # Add widgets to the grid
        self.add_widget(Button(text='Button 1'))
        self.add_widget(Button(text='Button 2'))
        self.add_widget(Button(text='Button 3'))
        self.add_widget(Button(text='Button 4'))

In the above code, we set the cols property of the GridLayout to 2, which specifies that we want 2 columns in our grid. Then, we add four buttons to the grid using the add_widget() method.

Running the Application

To see the GridLayout in action, we need to create an instance of the MyGridLayout class and run the Kivy application:

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

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

Save the above code in a Python file (e.g., main.py), and run it from the terminal:

python main.py

You should see a window with four buttons arranged in a 2-column grid pattern.

Customizing the GridLayout

You can customize the appearance and behavior of the GridLayout by modifying its properties. For example, you can adjust the spacing between widgets, their size, and other properties. Refer to the Kivy documentation for a complete list of properties and methods available for the GridLayout class.

Conclusion

The GridLayout layout manager in Kivy provides a convenient way to arrange widgets in a grid-like pattern. In this blog post, we learned how to use the GridLayout to create a simple grid layout and customize its properties.

The GridLayout is just one of the many layout managers available in Kivy, and each has its own unique features. Experiment with different layouts to create visually appealing and user-friendly interfaces for your applications.