[파이썬] Kivy `Label` 위젯

Kivy is an open-source Python framework for developing multi-touch applications. It provides a wide range of widgets that can be used to build dynamic and interactive user interfaces. One of the most commonly used widgets in Kivy is the Label widget.

The Label widget is used to display a textual message on the screen. It supports various text formatting options like bold, italic, and underlined text. Additionally, it can also display images and change its appearance based on different states.

Creating a Basic Label Widget

Here is an example of how to create a basic Label widget in Kivy:

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


class MyApp(App):
    def build(self):
        label = Label(text="Hello, Kivy!")
        return label


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

In the above code, we import the necessary classes from Kivy and define a simple Kivy application. Inside the build() method, we create an instance of the Label widget and set its text property to “Hello, Kivy!”. Finally, we return the label widget, which will be displayed on the screen when the application is run.

Customizing the Label Appearance

The Label widget in Kivy provides several attributes to customize its appearance. You can modify the font size, font color, font family, and text alignment. Here’s an example that demonstrates how to customize the appearance of a Label widget:

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


class MyApp(App):
    def build(self):
        label = Label(text="Kivy Label Widget", 
                      font_size='20sp', 
                      color=(1, 0, 0, 1), 
                      font_name='Arial', 
                      halign='center')
        return label


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

In the above code, we set the font_size attribute to '20sp', which specifies a font size of 20 scale-independent pixels. We also set the color attribute to (1, 0, 0, 1), which represents a red color (RGB values). The font_name attribute is set to 'Arial', specifying the font family to be used. Lastly, we set the halign attribute to 'center', which centers the text horizontally within the widget.

Conclusion

The Label widget is a versatile widget in Kivy that allows you to display textual messages in your applications. It provides various customization options, making it easy to style the widget to match your application’s design requirements.