Table Of Contents
Label¶
The Label widget is for rendering text:
# hello world text
l = Label(text='Hello world')
# unicode text; can only display glyphs that are available in the font
l = Label(text='Hello world ' + chr(2764))
# multiline text
l = Label(text='Multi\nLine')
# size
l = Label(text='Hello world', font_size='20sp')
Sizing and text content¶
By default, the size of Label is not affected by text
content and the text is not affected by the size. In order to control
sizing, you must specify text_size to constrain the text
and/or bind size to texture_size to grow with
the text.
For example, this label’s size will be set to the text content
(plus padding):
Label:
size: self.texture_size
This label’s text will wrap at the specified width and be clipped to the height:
Label:
text_size: cm(6), cm(4)
Note
The shorten and max_lines attributes
control how overflowing text behaves.
Combine these concepts to create a Label that can grow vertically but wraps the text at a certain width:
Label:
text_size: root.width, None
size: self.texture_size
How to have a custom background color in the label:
# Define your background color Template
<BackgroundColor@Widget>
background_color: 1, 1, 1, 1
canvas.before:
Color:
rgba: root.background_color
Rectangle:
size: self.size
pos: self.pos
# Now you can simply Mix the `BackgroundColor` class with almost
# any other widget... to give it a background.
<BackgroundLabel@Label+BackgroundColor>
background_color: 0, 0, 0, 0
# Default the background color for this label
# to r 0, g 0, b 0, a 0
# Use the BackgroundLabel any where in your kv code like below
BackgroundLabel
text: 'Hello'
background_color: 1, 0, 0, 1
Text alignment and wrapping¶
The Label has halign and valign
properties to control the alignment of its text. However, by default the text
image (texture) is only just large enough to contain the
characters and is positioned in the center of the Label. The valign property
will have no effect and halign will only have an effect if your text has
newlines; a single line of text will appear to be centered even though halign
is set to left (by default).
In order for the alignment properties to take effect, set the
text_size, which specifies the size of the bounding box within
which text is aligned. For instance, the following code binds this size to the
size of the Label, so text will be aligned within the widget bounds. This
will also automatically wrap the text of the Label to remain within this area.
Label:
text_size: self.size
halign: 'right'
valign: 'middle'
Markup text¶
New in version 1.1.0.
You can change the style of the text using Text Markup. The syntax is similar to the bbcode syntax but only the inline styling is allowed:
# hello world with world in bold
l = Label(text='Hello [b]World[/b]', markup=True)
# hello in red, world in blue
l = Label(text='[color=ff3333]Hello[/color][color=3333ff]World[/color]',
markup = True)
If you need to escape the markup from the current text, use
kivy.utils.escape_markup():
text = 'This is an important message [1]'
l = Label(text='[b]' + escape_markup(text) + '[/b]', markup=True)
The following tags are available:
[b][/b]Activate bold text
[i][/i]Activate italic text
[u][/u]Underlined text
[s][/s]Strikethrough text
[font=<str>][/font]Change the font (note: this refers to a TTF file or registered alias)
[font_context=<str>][/font_context]Change context for the font, use string value “none” for isolated context (this is equivalent to None; if you created a font context named ‘none’, it cannot be referred to using markup)
[font_family=<str>][/font_family]Font family to request for drawing. This is only valid when using a font context, see
kivy.uix.label.Labelfor details.[font_features=<str>][/font_features]OpenType font features, in CSS format, this is passed straight through to Pango. The effects of requesting a feature depends on loaded fonts, library versions, etc. Pango only, requires v1.38 or later.
[size=<integer>][/size]Change the font size
[color=#<color>][/color]Change the text color
[ref=<str>][/ref]Add an interactive zone. The reference + bounding box inside the reference will be available in
Label.refs[anchor=<str>]Put an anchor in the text. You can get the position of your anchor within the text with
Label.anchors[sub][/sub]Display the text at a subscript position relative to the text before it.
[sup][/sup]Display the text at a superscript position relative to the text before it.
[text_language=<str>][/text_language]Language of the text, this is an RFC-3066 format language tag (as string), for example “en_US”, “zh_CN”, “fr” or “ja”. This can impact font selection and metrics. Use the string “None” to revert to locale detection. Pango only.
If you want to render the markup text with a [ or ] or & character, you need to escape them. We created a simple syntax:
[ -> &bl;
] -> &br;
& -> &
Then you can write:
"[size=24]Hello &bl;World&br;[/size]"
Interactive zone in text¶
New in version 1.1.0.
You can now have definable “links” using text markup. The idea is to be able
to detect when the user clicks on part of the text and to react.
The tag [ref=xxx] is used for that.
In this example, we are creating a reference on the word “World”. When
this word is clicked, the function print_it will be called with the
name of the reference:
def print_it(instance, value):
print('User clicked on', value)
widget = Label(text='Hello [ref=world]World[/ref]', markup=True)
widget.bind(on_ref_press=print_it)
For prettier rendering, you could add a color for the reference. Replace the
text= in the previous example with:
'Hello [ref=world][color=0000ff]World[/color][/ref]'
Catering for Unicode languages¶
The font kivy uses does not contain all the characters required for displaying all languages. When you use the built-in widgets, this results in a block being drawn where you expect a character.
If you want to display such characters, you can chose a font that supports them and deploy it universally via kv:
<Label>:
font_name: '/<path>/<to>/<font>'
Note that this needs to be done before your widgets are loaded as kv rules are only applied at load time.
Usage example¶
The following example marks the anchors and references contained in a label:
from kivy.app import App
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.graphics import Color, Rectangle
class TestApp(App):
@staticmethod
def get_x(label, ref_x):
""" Return the x value of the ref/anchor relative to the canvas """
return label.center_x - label.texture_size[0] * 0.5 + ref_x
@staticmethod
def get_y(label, ref_y):
""" Return the y value of the ref/anchor relative to the canvas """
# Note the inversion of direction, as y values start at the top of
# the texture and increase downwards
return label.center_y + label.texture_size[1] * 0.5 - ref_y
def show_marks(self, label):
# Indicate the position of the anchors with a red top marker
for name, anc in label.anchors.items():
with label.canvas:
Color(1, 0, 0)
Rectangle(pos=(self.get_x(label, anc[0]),
self.get_y(label, anc[1])),
size=(3, 3))
# Draw a green surround around the refs. Note the sizes y inversion
for name, boxes in label.refs.items():
for box in boxes:
with label.canvas:
Color(0, 1, 0, 0.25)
Rectangle(pos=(self.get_x(label, box[0]),
self.get_y(label, box[1])),
size=(box[2] - box[0],
box[1] - box[3]))
def build(self):
label = Label(
text='[anchor=a]a\nChars [anchor=b]b\n[ref=myref]ref[/ref]',
markup=True)
Clock.schedule_once(lambda dt: self.show_marks(label), 1)
return label
TestApp().run()
- class kivy.uix.label.Label(**kwargs)¶
Bases:
kivy.uix.widget.WidgetLabel class, see module documentation for more information.
- Events:
- on_ref_press
Fired when the user clicks on a word referenced with a
[ref]tag in a text markup.
- on_touch_down(touch)¶
Receive a touch down event.
- Parameters:
- touch:
MotionEventclass Touch received. The touch is in parent coordinates. See
relativelayoutfor a discussion on coordinate systems.
- touch:
- Returns:
bool If True, the dispatching of the touch event will stop. If False, the event will continue to be dispatched to the rest of the widget tree.
- texture_update(*largs)¶
Force texture recreation with the current Label properties.
After this function call, the
textureandtexture_sizewill be updated in this order.