Label#

#

The MDLabel widget is for rendering text.

https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/label.png

MDLabel#

Example#

from kivy.lang import Builder

from kivymd.app import MDApp

KV = '''
MDScreen:
    md_bg_color: self.theme_cls.backgroundColor

    MDLabel:
        text: "MDLabel"
        halign: "center"
'''


class Example(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        return Builder.load_string(KV)


Example().run()
https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/label-example.png

To use a custom color for MDLabel, use a theme ‘Custom’. After that, you can specify the desired color in the text_color parameter:

MDLabel:
    text: "Custom color"
    halign: "center"
    theme_text_color: "Custom"
    text_color: "red"
https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/md-label-custom-color.png

MDLabel provides standard font styles for labels. To do this, specify the name of the desired style in the font_style and role parameters:

MDLabel:
    text: "Display, role - 'large'"
    font_style: "Display"
https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/md-label-font-style-display-large.png
MDLabel:
    text: "Display, role - 'small'"
    font_style: "Display"
    role: "small"
https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/md-label-font-style-display-small.png

All styles#

from kivy.lang import Builder

from kivymd.font_definitions import theme_font_styles
from kivymd.app import MDApp

KV = '''
MDScreen:
    md_bg_color: self.theme_cls.backgroundColor

    MDRecycleView:
        id: rv
        key_viewclass: 'viewclass'
        key_size: 'height'

        RecycleBoxLayout:
            padding: dp(10)
            spacing: dp(10)
            default_size: None, dp(48)
            default_size_hint: 1, None
            size_hint_y: None
            height: self.minimum_height
            orientation: "vertical"
'''


class Example(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        return Builder.load_string(KV)

    def on_start(self):
        for style in theme_font_styles:
            if style != "Icon":
                for role in theme_font_styles[style]:
                    font_size = int(theme_font_styles[style][role]["font-size"])
                    self.root.ids.rv.data.append(
                        {
                            "viewclass": "MDLabel",
                            "text": f"{style} {role} {font_size} sp",
                            "adaptive_height": "True",
                            "font_style": style,
                            "role": role,
                        }
                    )


Example().run()
https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/label-font-style-preview.png

Highlighting and copying labels#

You can highlight labels by double tap on the label:#

from kivy.lang.builder import Builder

from kivymd.app import MDApp

KV = '''
MDScreen:
    md_bg_color: self.theme_cls.backgroundColor

    MDLabel:
        adaptive_size: True
        pos_hint: {"center_x": .5, "center_y": .5}
        text: "Do a double click on me"
        allow_selection: True
        padding: "4dp", "4dp"
'''


class Example(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        return Builder.load_string(KV)


Example().run()
https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/md-label-allow-selection.gif

You can copy the label text by double clicking on it:#

from kivy.lang.builder import Builder

from kivymd.app import MDApp

KV = '''
MDScreen:

    MDLabel:
        adaptive_size: True
        pos_hint: {"center_x": .5, "center_y": .5}
        text: "MDLabel"
        padding: "4dp", "4dp"
        allow_selection: True
        allow_copy: True
        on_copy: print("The text is copied to the clipboard")
'''


class Example(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Orange"
        return Builder.load_string(KV)


Example().run()

Example of copying/cutting labels using the context menu#

from kivy.core.clipboard import Clipboard
from kivy.lang.builder import Builder
from kivy.metrics import dp

from kivymd.uix.snackbar import MDSnackbar, MDSnackbarText
from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
from kivymd.uix.menu import MDDropdownMenu

KV = '''
MDBoxLayout:
    orientation: "vertical"
    spacing: "12dp"
    padding: "24dp"
    md_bg_color: self.theme_cls.backgroundColor

    MDBoxLayout:
        id: box
        orientation: "vertical"
        padding: "24dp"
        spacing: "12dp"
        adaptive_height: True

    MDTextField:
        max_height: "200dp"
        mode: "filled"
        multiline: True

    Widget:
'''

data = [
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    "Sed blandit libero volutpat sed cras ornare arcu. Nisl vel pretium "
    "lectus quam id leo in. Tincidunt arcu non sodales neque sodales ut etiam.",
    "Elit scelerisque mauris pellentesque pulvinar pellentesque habitant. "
    "Nisl rhoncus mattis rhoncus urna neque. Orci nulla pellentesque "
    "dignissim enim. Ac auctor augue mauris augue neque gravida in fermentum. "
    "Lacus suspendisse faucibus interdum posuere."
]


def toast(text):
    MDSnackbar(
        MDSnackbarText(
            text=text,
        ),
        y=dp(24),
        pos_hint={"center_x": 0.5},
        size_hint_x=0.3,
    ).open()


class CopyLabel(MDLabel):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.allow_selection = True
        self.adaptive_height = True


class Example(MDApp):
    context_menu = None

    def build(self):
        return Builder.load_string(KV)

    def on_start(self):
        for text in data:
            copy_label = CopyLabel(text=text)
            copy_label.bind(on_selection=self.open_context_menu)
            self.root.ids.box.add_widget(copy_label)

    def click_item_context_menu(
        self, type_click: str, instance_label: CopyLabel
    ) -> None:
        Clipboard.copy(instance_label.text)

        if type_click == "copy":
            toast("Copied")
        elif type_click == "cut":
            self.root.ids.box.remove_widget(instance_label)
            toast("Cut")
        if self.context_menu:
            self.context_menu.dismiss()

    def open_context_menu(self, instance_label: CopyLabel) -> None:
        instance_label.text_color = "black"
        menu_items = [
            {
                "text": "Copy text",
                "on_release": lambda: self.click_item_context_menu(
                    "copy", instance_label
                ),
            },
            {
                "text": "Cut text",
                "on_release": lambda: self.click_item_context_menu(
                    "cut", instance_label
                ),
            },
        ]
        self.context_menu = MDDropdownMenu(
            caller=instance_label, items=menu_items, width_mult=3
        )
        self.context_menu.open()


Example().run()
https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/copying-cutting-labels-using-context-menu.gif

MDIcon#

You can use labels to display material design icons using the MDIcon class.

The MDIcon class is inherited from MDLabel and has the same parameters.

Warning

For the MDIcon class, you cannot use text and font_style options!

MDIcon:
    icon: "gmail"
https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/md-icon.png

MDIcon with badge icon#

MDIcon:
    icon: "gmail"

    MDBadge:
        text: "10+"
https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/md-icon-badge.png

MDIcon with a custom font icon#

You can use custom fonts to display icons. Such as for example Material Symbols. You can find the necessary fonts in the materialsymbols-python repository

from kivy.core.text import LabelBase
from kivy.lang import Builder
from kivy.metrics import sp

from kivymd.app import MDApp

KV = '''
MDScreen:
    md_bg_color: self.theme_cls.backgroundColor

    MDIcon:
        icon: "music_video"
        theme_font_name: "Custom"
        font_name: "MaterialSymbols"
        pos_hint: {"center_x": .5, "center_y": .58}

    MDButton:
        pos_hint: {"center_x": .5, "center_y": .47}

        MDButtonIcon:
            icon: "music_video"
            theme_font_name: "Custom"
            font_name: "MaterialSymbols"

        MDButtonText:
            text: "Elevated"
'''


class Example(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"

        LabelBase.register(
            name="MaterialSymbols",
            fn_regular="Material_Symbols_Outlined-20-200-1_200.ttf",
        )

        self.theme_cls.font_styles["MaterialSymbols"] = {
            "large": {
                "line-height": 1.64,
                "font-name": "MaterialSymbols",
                "font-size": sp(57),
            },
            "medium": {
                "line-height": 1.52,
                "font-name": "MaterialSymbols",
                "font-size": sp(45),
            },
            "small": {
                "line-height": 1.44,
                "font-name": "MaterialSymbols",
                "font-size": sp(36),
            },
        }

        return Builder.load_string(KV)


Example().run()
https://github.com/HeaTTheatR/KivyMD-data/raw/master/gallery/kivymddoc/md-icon-castom-font.png

API - kivymd.uix.label.label#

class kivymd.uix.label.label.MDLabel(*args, **kwargs)#

Label class.

For more information, see in the DeclarativeBehavior and ThemableBehavior and BackgroundColorBehavior and Label and MDAdaptiveWidget and TouchBehavior and StateLayerBehavior classes documentation.

Events:
on_ref_press

Fired when the user clicks on a word referenced with a [ref] tag in a text markup.

on_copy

Fired when double-tapping on the label.

on_selection

Fired when double-tapping on the label.

on_cancel_selection

Fired when the highlighting is removed from the label text.

font_style#

Label font style.

Changed in version 2.0.0.

Available vanilla font_style are: ‘Display’, ‘Headline’, ‘Title’, ‘Label’, ‘Body’`.

font_style is an StringProperty and defaults to ‘Body’.

role#

Role of font style.

Added in version 2.0.0.

Available options are: ‘large’, ‘medium’, ‘small’.

role is an StringProperty and defaults to ‘large’.

text#

Text of the label.

text is an StringProperty and defaults to ‘’.

text_color#

Label text color in (r, g, b, a) or string format.

text_color is an ColorProperty and defaults to None.

allow_copy#

Allows you to copy text to the clipboard by double-clicking on the label.

Added in version 1.2.0.

allow_copy is an BooleanProperty and defaults to False.

allow_selection#

Allows to highlight text by double-clicking on the label.

Added in version 1.2.0.

allow_selection is an BooleanProperty and defaults to False.

color_selection#

The color in (r, g, b, a) or string format of the text selection when the value of the allow_selection attribute is True.

Added in version 1.2.0.

color_selection is an ColorProperty and defaults to None.

color_deselection#

The color in (r, g, b, a) or string format of the text deselection when the value of the allow_selection attribute is True.

Added in version 1.2.0.

color_deselection is an ColorProperty and defaults to None.

is_selected#

Is the label text highlighted.

Added in version 1.2.0.

is_selected is an BooleanProperty and defaults to False.

radius#

Label radius.

radius is an VariableListProperty and defaults to [0, 0, 0, 0].

do_selection() None#
cancel_selection() None#
on_double_tap(touch, *args) None#

Fired by double-clicking on the widget.

on_window_touch(*args) None#

Fired at the on_touch_down event.

on_copy(*args) None#

Fired when double-tapping on the label.

Added in version 1.2.0.

on_selection(*args) None#

Fired when double-tapping on the label.

Added in version 1.2.0.

on_cancel_selection(*args) None#

Fired when the highlighting is removed from the label text.

Added in version 1.2.0.

on_allow_selection(instance_label, selection: bool) None#

Fired when the allow_selection value changes.

on_text_color(instance_label, color: list | str) None#

Fired when the text_color value changes.

on_md_bg_color(instance_label, color: list | str) None#

Fired when the md_bg_color value changes.

on_size(instance_label, size: list) None#

Fired when the parent window of the application is resized.

update_canvas_bg_pos(instance_label, pos: list) None#
class kivymd.uix.label.label.MDIcon(*args, **kwargs)#

Icon class.

For more information, see in the MDLabel class documentation.

icon#

Label icon name.

icon is an StringProperty and defaults to ‘blank’.

source#

Path to icon.

source is an StringProperty and defaults to None.

icon_color#

Icon color in (r, g, b, a) or string format.

Added in version 2.0.0.

icon_color is a ColorProperty and defaults to None.

icon_color_disabled#

The icon color in (r, g, b, a) or string format of the button when the button is disabled.

Added in version 2.0.0.

icon_color_disabled is a ColorProperty and defaults to None.

add_widget(widget, index=0, canvas=None)#

Add a new widget as a child of this widget.

Parameters:
widget: Widget

Widget to add to our list of children.

index: int, defaults to 0

Index to insert the widget in the list. Notice that the default of 0 means the widget is inserted at the beginning of the list and will thus be drawn on top of other sibling widgets. For a full discussion of the index and widget hierarchy, please see the Widgets Programming Guide.

Added in version 1.0.5.

canvas: str, defaults to None

Canvas to add widget’s canvas to. Can be ‘before’, ‘after’ or None for the default canvas.

Added in version 1.9.0.

>>> from kivy.uix.button import Button
>>> from kivy.uix.slider import Slider
>>> root = Widget()
>>> root.add_widget(Button())
>>> slider = Slider()
>>> root.add_widget(slider)