Как изменить шрифт kivy

An abstraction of text creation. Depending of the selected backend, the accuracy of text rendering may vary.

Table Of Contents

  • Text
    • Font Context Manager

An abstraction of text creation. Depending of the selected backend, the
accuracy of text rendering may vary.

Changed in version 1.10.1: LabelBase.find_base_direction() added.

Changed in version 1.5.0: LabelBase.line_height added.

Changed in version 1.0.7: The LabelBase does not generate any texture if the text has a
width <= 1.

This is the backend layer for rendering text with different text providers,
you should only be using this directly if your needs aren’t fulfilled by the
Label.

Usage example:

from kivy.core.text import Label as CoreLabel

...
...
my_label = CoreLabel()
my_label.text = 'hello'
# the label is usually not drawn until needed, so force it to draw.
my_label.refresh()
# Now access the texture of the label and use it wherever and
# however you may please.
hello_texture = my_label.texture

Font Context Manager¶

A font context is a namespace where multiple fonts are loaded; if a font is
missing a glyph needed to render text, it can fall back to a different font in
the same context. The font context manager can be used to query and manipulate
the state of font contexts when using the Pango text provider (no other
provider currently implements it).

New in version 1.11.0.

Warning

This feature requires the Pango text provider.

Font contexts can be created automatically by kivy.uix.label.Label or
kivy.uix.textinput.TextInput; if a non-existent context is used in
one of these classes, it will be created automatically, or if a font file is
specified without a context (this creates an isolated context, without
support for fallback).

Usage example:

from kivy.uix.label import Label
from kivy.core.text import FontContextManager as FCM

# Create a font context containing system fonts + one custom TTF
FCM.create('system://myapp')
family = FCM.add_font('/path/to/file.ttf')

# These are now interchangeable ways to refer to the custom font:
lbl1 = Label(font_context='system://myapp', family_name=family)
lbl2 = Label(font_context='system://myapp', font_name='/path/to/file.ttf')

# You could also refer to a system font by family, since this is a
# system:// font context
lbl3 = Label(font_context='system://myapp', family_name='Arial')
class kivy.core.text.LabelBase(text=», font_size=12, font_name=None, bold=False, italic=False, underline=False, strikethrough=False, font_family=None, halign=‘left’, valign=‘bottom’, shorten=False, text_size=None, mipmap=False, color=None, line_height=1.0, strip=False, strip_reflow=True, shorten_from=‘center’, split_str= , unicode_errors=‘replace’, font_hinting=‘normal’, font_kerning=True, font_blended=True, outline_width=None, outline_color=None, font_context=None, font_features=None, base_direction=None, text_language=None, **kwargs)[source]

Bases: builtins.object

Core text label.
This is the abstract class used by different backends to render text.

Warning

The core text label can’t be changed at runtime. You must recreate one.

Parameters
font_size: int, defaults to 12

Font size of the text

font_context: str, defaults to None

Context for the specified font (see kivy.uix.label.Label
for details). None will autocreate an isolated context named
after the resolved font file.

font_name: str, defaults to DEFAULT_FONT

Font name of the text

font_family: str, defaults to None

Font family name to request for drawing, this can only be used
with font_context.

bold: bool, defaults to False

Activate “bold” text style

italic: bool, defaults to False

Activate “italic” text style

text_size: tuple, defaults to (None, None)

Add constraint to render the text (inside a bounding box).
If no size is given, the label size will be set to the text size.

padding: float, defaults to None

If it’s a float, it will set padding_x and padding_y

padding_x: float, defaults to 0.0

Left/right padding

padding_y: float, defaults to 0.0

Top/bottom padding

halign: str, defaults to “left”

Horizontal text alignment inside the bounding box

valign: str, defaults to “bottom”

Vertical text alignment inside the bounding box

shorten: bool, defaults to False

Indicate whether the label should attempt to shorten its textual
contents as much as possible if a size is given.
Setting this to True without an appropriately set size will lead to
unexpected results.

shorten_from: str, defaults to center

The side from which we should shorten the text from, can be left,
right, or center. E.g. if left, the ellipsis will appear towards
the left side and it will display as much text starting from the
right as possible.

split_str: string, defaults to ‘ ‘ (space)

The string to use to split the words by when shortening. If empty,
we can split after every character filling up the line as much as
possible.

max_lines: int, defaults to 0 (unlimited)

If set, this indicate how maximum line are allowed to render the
text. Works only if a limitation on text_size is set.

mipmap: bool, defaults to False

Create a mipmap for the texture

strip: bool, defaults to False

Whether each row of text has its leading and trailing spaces
stripped. If halign is justify it is implicitly True.

strip_reflow: bool, defaults to True

Whether text that has been reflowed into a second line should
be stripped, even if strip is False. This is only in effect when
size_hint_x is not None, because otherwise lines are never
split.

unicode_errors: str, defaults to ‘replace’

How to handle unicode decode errors. Can be ‘strict’, ‘replace’
or ‘ignore’.

outline_width: int, defaults to None

Width in pixels for the outline.

outline_color: tuple, defaults to (0, 0, 0)

Color of the outline.

font_features: str, defaults to None

OpenType font features in CSS format (Pango only)

base_direction: str, defaults to None (auto)

Text direction, one of None, ‘ltr’, ‘rtl’, ‘weak_ltr’,
or ‘weak_rtl’ (Pango only)

text_language: str, defaults to None (user locale)

RFC-3066 format language tag as a string (Pango only)

Changed in version 1.10.1: font_context, font_family, font_features, base_direction
and text_language were added.

Changed in version 1.10.0: outline_width and outline_color were added.

Changed in version 1.9.0: strip, strip_reflow, shorten_from, split_str, and
unicode_errors were added.

Changed in version 1.9.0: padding_x and padding_y has been fixed to work as expected.
In the past, the text was padded by the negative of their values.

Changed in version 1.8.0: max_lines parameters has been added.

Changed in version 1.0.8: size have been deprecated and replaced with text_size.

Changed in version 1.0.7: The valign is now respected. This wasn’t the case previously
so you might have an issue in your application if you have not
considered this.

property content_height

Return the content height; i.e. the height of the text without
any padding.

property content_size

Return the content size (width, height)

property content_width

Return the content width; i.e. the width of the text without
any padding.

static find_base_direction(text)[source]

Searches a string the first character that has a strong direction,
according to the Unicode bidirectional algorithm. Returns None if
the base direction cannot be determined, or one of ‘ltr’ or ‘rtl’.

Note

This feature requires the Pango text provider.

property fontid

Return a unique id for all font parameters

get_cached_extents()[source]

Returns a cached version of the get_extents() function.

>>> func = self._get_cached_extents()
>>> func
<built-in method size of pygame.font.Font object at 0x01E45650>
>>> func('a line')
(36, 18)

Warning

This method returns a size measuring function that is valid
for the font settings used at the time get_cached_extents()
was called. Any change in the font settings will render the
returned function incorrect. You should only use this if you know
what you’re doing.

New in version 1.9.0.

get_extents(text)[source]

Return a tuple (width, height) indicating the size of the specified
text

static get_system_fonts_dir()[source]

Return the directories used by the system for fonts.

property label

Get/Set the text

refresh()[source]

Force re-rendering of the text

static register(name, fn_regular, fn_italic=None, fn_bold=None, fn_bolditalic=None)[source]

Register an alias for a Font.

New in version 1.1.0.

If you’re using a ttf directly, you might not be able to use the
bold/italic properties of
the ttf version. If the font is delivered in multiple files
(one regular, one italic and one bold), then you need to register these
files and use the alias instead.

All the fn_regular/fn_italic/fn_bold parameters are resolved with
kivy.resources.resource_find(). If fn_italic/fn_bold are None,
fn_regular will be used instead.

render(real=False)[source]

Return a tuple (width, height) to create the image
with the user constraints. (width, height) includes the padding.

shorten(text, margin=2)[source]

Shortens the text to fit into a single line by the width specified
by text_size [0]. If text_size [0] is None, it returns
text text unchanged.

split_str and shorten_from determines how the text is
shortened.

Params

text str, the text to be shortened.
margin int, the amount of space to leave between the margins
and the text. This is in addition to padding_x.

Returns

the text shortened to fit into a single line.

property text

Get/Set the text

property text_size

Get/set the (width, height) of the ‘
‘contrained rendering box

property usersize

(deprecated) Use text_size instead.

  • Text layout
  • Text Markup

Table Of Contents

  • Label
    • Sizing and text content
    • Text alignment and wrapping
    • Markup text
    • Interactive zone in text
    • Catering for Unicode languages
    • Usage example

_images/label.png

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='MultinLine')

# 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.Label for 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;
&   -> &amp;

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]anChars [anchor=b]bn[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)[source]

Bases: kivy.uix.widget.Widget

Label 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.

anchors

New in version 1.1.0.

Position of all the [anchor=xxx] markup in the text.
These coordinates are relative to the top left corner of the text, with
the y value increasing downwards. Anchors names should be unique and only
the first occurrence of any duplicate anchors will be recorded.

You can place anchors in your markup text as follows:

text = """
    [anchor=title1][size=24]This is my Big title.[/size]
    [anchor=content]Hello world
"""

Then, all the [anchor=] references will be removed and you’ll get all
the anchor positions in this property (only after rendering):

>>> widget = Label(text=text, markup=True)
>>> widget.texture_update()
>>> widget.anchors
{"content": (20, 32), "title1": (20, 16)}

Note

This works only with markup text. You need markup set to
True.

base_direction

Base direction of text, this impacts horizontal alignment when
halign is auto (the default). Available options are: None,
“ltr” (left to right), “rtl” (right to left) plus “weak_ltr” and
“weak_rtl”.

Note

This feature requires the Pango text provider.

Note

Weak modes are currently not implemented in Kivy text layout, and
have the same effect as setting strong mode.

New in version 1.11.0.

base_direction is an OptionProperty and
defaults to None (autodetect RTL if possible, otherwise LTR).

bold

Indicates use of the bold version of your font.

Note

Depending of your font, the bold attribute may have no impact on your
text rendering.

bold is a BooleanProperty and defaults to
False.

color

Text color, in the format (r, g, b, a).

color is a ColorProperty and defaults to
[1, 1, 1, 1].

disabled_color

The color of the text when the widget is disabled, in the (r, g, b, a)
format.

New in version 1.8.0.

disabled_color is a ColorProperty and
defaults to [1, 1, 1, .3].

disabled_outline_color

The color of the text outline when the widget is disabled, in the
(r, g, b) format.

Note

This feature requires the SDL2 text provider.

New in version 1.10.0.

disabled_outline_color is a ColorProperty
and defaults to [0, 0, 0].

Changed in version 2.0.0: Changed from ListProperty to
ColorProperty. Alpha component is ignored
and assigning value to it has no effect.

ellipsis_options

Font options for the ellipsis string(’…’) used to split the text.

Accepts a dict as option name with the value. Only applied when
markup is true and text is shortened. All font options which work
for Label will work for ellipsis_options. Defaults for
the options not specified are taken from the surronding text.

Label:
    text: 'Some very long line which will be cut'
    markup: True
    shorten: True
    ellipsis_options: {'color':(1,0.5,0.5,1),'underline':True}

New in version 2.0.0.

ellipsis_options is a DictProperty and
defaults to {} (the empty dict).

font_blended

Whether blended or solid font rendering should be used.

Note

This feature requires the SDL2 text provider.

New in version 1.10.0.

font_blended is a BooleanProperty and
defaults to True.

font_context

Font context. None means the font is used in isolation, so you are
guaranteed to be drawing with the TTF file resolved by font_name.
Specifying a value here will load the font file into a named context,
enabling fallback between all fonts in the same context. If a font
context is set, you are not guaranteed that rendering will actually use
the specified TTF file for all glyphs (Pango will pick the one it
thinks is best).

If Kivy is linked against a system-wide installation of FontConfig,
you can load the system fonts by specifying a font context starting
with the special string system://. This will load the system
fontconfig configuration, and add your application-specific fonts on
top of it (this imposes a signifficant risk of family name collision,
Pango may not use your custom font file, but pick one from the system)

Note

This feature requires the Pango text provider.

New in version 1.11.0.

font_context is a StringProperty and
defaults to None.

font_family

Font family, this is only applicable when using font_context
option. The specified font family will be requested, but note that it may
not be available, or there could be multiple fonts registered with the
same family. The value can be a family name (string) available in the
font context (for example a system font in a system:// context, or a
custom font file added using kivy.core.text.FontContextManager).
If set to None, font selection is controlled by the font_name
setting.

Note

If using font_name to reference a custom font file, you
should leave this as None. The family name is managed automatically
in this case.

Note

This feature requires the Pango text provider.

New in version 1.11.0.

font_family is a StringProperty and
defaults to None.

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. For a complete list of features, see:

https://en.wikipedia.org/wiki/List_of_typographic_features

Note

This feature requires the Pango text provider, and Pango library
v1.38 or later.

New in version 1.11.0.

font_features is a StringProperty and
defaults to an empty string.

font_hinting

What hinting option to use for font rendering.
Can be one of ‘normal’, ‘light’, ‘mono’ or None.

Note

This feature requires SDL2 or Pango text provider.

New in version 1.10.0.

font_hinting is an OptionProperty and
defaults to ‘normal’.

font_kerning

Whether kerning is enabled for font rendering. You should normally
only disable this if rendering is broken with a particular font file.

Note

This feature requires the SDL2 text provider.

New in version 1.10.0.

font_kerning is a BooleanProperty and
defaults to True.

font_name

Filename of the font to use. The path can be absolute or relative.
Relative paths are resolved by the resource_find()
function.

Warning

Depending of your text provider, the font file can be ignored. However,
you can mostly use this without problems.

If the font used lacks the glyphs for the particular language/symbols
you are using, you will see ‘[]’ blank box characters instead of the
actual glyphs. The solution is to use a font that has the glyphs you
need to display. For example, to display unicodechar, use a font such
as freesans.ttf that has the glyph.

font_name is a StringProperty and
defaults to ‘Roboto’. This value is taken
from Config.

font_size

Font size of the text, in pixels.

font_size is a NumericProperty and
defaults to 15sp.

halign

Horizontal alignment of the text.

halign is an OptionProperty and
defaults to ‘auto’. Available options are : auto, left, center, right and
justify. Auto will attempt to autodetect horizontal alignment for RTL text
(Pango only), otherwise it behaves like left.

Warning

This doesn’t change the position of the text texture of the Label
(centered), only the position of the text in this texture. You probably
want to bind the size of the Label to the texture_size or set a
text_size.

Changed in version 1.10.1: Added auto option

Changed in version 1.6.0: A new option was added to halign, namely justify.

is_shortened

This property indicates if text was rendered with or without
shortening when shorten is True.

New in version 1.10.0.

is_shortened is a BooleanProperty and
defaults to False.

italic

Indicates use of the italic version of your font.

Note

Depending of your font, the italic attribute may have no impact on your
text rendering.

italic is a BooleanProperty and defaults
to False.

line_height

Line Height for the text. e.g. line_height = 2 will cause the spacing
between lines to be twice the size.

line_height is a NumericProperty and
defaults to 1.0.

New in version 1.5.0.

markup

New in version 1.1.0.

If True, the text will be rendered using the
MarkupLabel: you can change the
style of the text using tags. Check the
Text Markup documentation for more information.

markup is a BooleanProperty and defaults
to False.

max_lines

Maximum number of lines to use, defaults to 0, which means unlimited.
Please note that shorten take over this property. (with
shorten, the text is always one line.)

New in version 1.8.0.

max_lines is a NumericProperty and
defaults to 0.

mipmap

Indicates whether OpenGL mipmapping is applied to the texture or not.
Read Mipmapping for more information.

New in version 1.0.7.

mipmap is a BooleanProperty and defaults
to False.

on_touch_down(touch)[source]

Receive a touch down event.

Parameters
touch: MotionEvent class

Touch received. The touch is in parent coordinates. See
relativelayout for a discussion on
coordinate systems.

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.

outline_color

The color of the text outline, in the (r, g, b) format.

Note

This feature requires the SDL2 text provider.

New in version 1.10.0.

outline_color is a ColorProperty and
defaults to [0, 0, 0, 1].

Changed in version 2.0.0: Changed from ListProperty to
ColorProperty. Alpha component is ignored
and assigning value to it has no effect.

outline_width

Width in pixels for the outline around the text. No outline will be
rendered if the value is None.

Note

This feature requires the SDL2 text provider.

New in version 1.10.0.

outline_width is a NumericProperty and
defaults to None.

padding

Padding of the text in the format (padding_x, padding_y)

padding is a ReferenceListProperty of
(padding_x, padding_y) properties.

padding_x

Horizontal padding of the text inside the widget box.

padding_x is a NumericProperty and
defaults to 0.

Changed in version 1.9.0: padding_x has been fixed to work as expected.
In the past, the text was padded by the negative of its values.

padding_y

Vertical padding of the text inside the widget box.

padding_y is a NumericProperty and
defaults to 0.

Changed in version 1.9.0: padding_y has been fixed to work as expected.
In the past, the text was padded by the negative of its values.

refs

New in version 1.1.0.

List of [ref=xxx] markup items in the text with the bounding box of
all the words contained in a ref, available only after rendering.

For example, if you wrote:

Check out my [ref=hello]link[/ref]

The refs will be set with:

{'hello': ((64, 0, 78, 16), )}

The references marked “hello” have a bounding box at (x1, y1, x2, y2).
These coordinates are relative to the top left corner of the text, with
the y value increasing downwards. You can define multiple refs with the
same name: each occurrence will be added as another (x1, y1, x2, y2) tuple
to this list.

The current Label implementation uses these references if they exist in
your markup text, automatically doing the collision with the touch and
dispatching an on_ref_press event.

You can bind a ref event like this:

def print_it(instance, value):
    print('User click on', value)
widget = Label(text='Hello [ref=world]World[/ref]', markup=True)
widget.bind(on_ref_press=print_it)

Note

This works only with markup text. You need markup set to
True.

shorten

Indicates whether the label should attempt to shorten its textual contents
as much as possible if a text_size is given. Setting this to True
without an appropriately set text_size will lead to unexpected
results.

shorten_from and split_str control the direction from
which the text is split, as well as where in the text we
are allowed to split.

shorten is a BooleanProperty and defaults
to False.

shorten_from

The side from which we should shorten the text from, can be left,
right, or center.

For example, if left, the ellipsis will appear towards the left side and we
will display as much text starting from the right as possible. Similar to
shorten, this option only applies when text_size [0] is
not None, In this case, the string is shortened to fit within the specified
width.

New in version 1.9.0.

shorten_from is a OptionProperty and
defaults to center.

split_str

The string used to split the text while shortening the string
when shorten is True.

For example, if it’s a space, the string will be broken into words and as
many whole words that can fit into a single line will be displayed. If
split_str is the empty string, ‘’, we split on every character
fitting as much text as possible into the line.

New in version 1.9.0.

split_str is a StringProperty and
defaults to ‘’ (the empty string).

strikethrough

Adds a strikethrough line to the text.

Note

This feature requires the SDL2 text provider.

New in version 1.10.0.

strikethrough is a BooleanProperty and
defaults to False.

strip

Whether leading and trailing spaces and newlines should be stripped from
each displayed line. If True, every line will start at the right or left
edge, depending on halign. If halign is justify it is
implicitly True.

New in version 1.9.0.

strip is a BooleanProperty and
defaults to False.

text

Text of the label.

Creation of a simple hello world:

widget = Label(text='Hello world')

text is a StringProperty and defaults to
‘’.

text_language

Language of the text, if None Pango will determine it from locale.
This is an RFC-3066 format language tag (as a string), for example
“en_US”, “zh_CN”, “fr” or “ja”. This can impact font selection, metrics
and rendering. For example, the same bytes of text can look different
for ur and ar languages, though both use Arabic script.

Note

This feature requires the Pango text provider.

New in version 1.11.0.

text_language is a StringProperty and
defaults to None.

text_size

By default, the label is not constrained to any bounding box.
You can set the size constraint of the label with this property.
The text will autoflow into the constraints. So although the font size
will not be reduced, the text will be arranged to fit into the box as best
as possible, with any text still outside the box clipped.

This sets and clips texture_size to text_size if not None.

New in version 1.0.4.

For example, whatever your current widget size is, if you want the label to
be created in a box with width=200 and unlimited height:

Label(text='Very big big line', text_size=(200, None))

Note

This text_size property is the same as the
usersize property in the
Label class. (It is named size= in the
constructor.)

text_size is a ListProperty and
defaults to (None, None), meaning no size restriction by default.

texture

Texture object of the text.
The text is rendered automatically when a property changes. The OpenGL
texture created in this operation is stored in this property. You can use
this texture for any graphics elements.

Depending on the texture creation, the value will be a
Texture or
TextureRegion object.

Warning

The texture update is scheduled for the next frame. If you need
the texture immediately after changing a property, you have to call
the texture_update() method before accessing texture:

l = Label(text='Hello world')
# l.texture is good
l.font_size = '50sp'
# l.texture is not updated yet
l.texture_update()
# l.texture is good now.

texture is an ObjectProperty and defaults
to None.

texture_size

Texture size of the text. The size is determined by the font size and
text. If text_size is [None, None], the texture will be the size
required to fit the text, otherwise it’s clipped to fit text_size.

When text_size is [None, None], one can bind to texture_size
and rescale it proportionally to fit the size of the label in order to
make the text fit maximally in the label.

Warning

The texture_size is set after the texture
property. If you listen for changes to texture,
texture_size will not be up-to-date in your callback.
Bind to texture_size instead.

texture_update(*largs)[source]

Force texture recreation with the current Label properties.

After this function call, the texture and texture_size
will be updated in this order.

underline

Adds an underline to the text.

Note

This feature requires the SDL2 text provider.

New in version 1.10.0.

underline is a BooleanProperty and
defaults to False.

unicode_errors

How to handle unicode decode errors. Can be ‘strict’, ‘replace’ or
‘ignore’.

New in version 1.9.0.

unicode_errors is an OptionProperty and
defaults to ‘replace’.

valign

Vertical alignment of the text.

valign is an OptionProperty and defaults
to ‘bottom’. Available options are : ‘bottom’,
‘middle’ (or ‘center’) and ‘top’.

Changed in version 1.10.0: The ‘center’ option has been added as an alias of ‘middle’.

Warning

This doesn’t change the position of the text texture of the Label
(centered), only the position of the text within this texture. You
probably want to bind the size of the Label to the texture_size
or set a text_size to change this behavior.

Use a template to create your custom Label:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget 
from kivy.properties import ObjectProperty, NumericProperty

kv = '''
[MyLabel@Label]:
    text: ctx.text if hasattr(ctx, 'text') else ''
    font_size: 24
    markup: True

<MyWidget>:
    id: f_wid
    BoxLayout:
        size: f_wid.size
        orientation: 'vertical'
        MyLabel:
            text: "Hello world 1"
        MyLabel:
            text: "Hello world 2"
        MyLabel:
            text: "Hello world 3"
        MyLabel:
            text: "Hello world 4"   
        MyLabel:
            text: "Hello world 1"
        MyLabel:
            text: "Hello world 2"
        MyLabel:
            text: "Hello world 3"
        MyLabel:
            text: "Hello world 4"   
'''
Builder.load_string(kv)

import kivy
kivy.require('1.7.1') # replace with your current kivy version !

from kivy.app import App
from kivy.uix.widget import Widget

class MyWidget(Widget):
    pass

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

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

To have font size depended on screen size, instead of using fixed values calculate it using self.heigh:

[MyLabel@Label]:
    text: ctx.text if hasattr(ctx, 'text') else ''
    font_size: self.height/2
    markup: True

UPDATE

Alternative approach is setting variable using #:set syntax:

kv = '''
#:set default_font_size "36sp"
<MyWidget>:
    id: f_wid
    BoxLayout:
        size: f_wid.size
        orientation: 'vertical'
        Label:
            text: "Hello world 1"
            font_size: default_font_size
        Label:
            text: "Hello world 2"
            font_size: default_font_size
        Label:
            text: "Hello world 3"
            font_size: default_font_size
        Label:
            text: "Hello world 4"   
            font_size: default_font_size
        Label:
            text: "Hello world 1"
            font_size: default_font_size
        Label:
            text: "Hello world 2"
            font_size: default_font_size
        Label:
            text: "Hello world 3"
            font_size: default_font_size
        Label:
            text: "Hello world 4"   
            font_size: default_font_size
'''
Builder.load_string(kv)

Use a template to create your custom Label:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget 
from kivy.properties import ObjectProperty, NumericProperty

kv = '''
[MyLabel@Label]:
    text: ctx.text if hasattr(ctx, 'text') else ''
    font_size: 24
    markup: True

<MyWidget>:
    id: f_wid
    BoxLayout:
        size: f_wid.size
        orientation: 'vertical'
        MyLabel:
            text: "Hello world 1"
        MyLabel:
            text: "Hello world 2"
        MyLabel:
            text: "Hello world 3"
        MyLabel:
            text: "Hello world 4"   
        MyLabel:
            text: "Hello world 1"
        MyLabel:
            text: "Hello world 2"
        MyLabel:
            text: "Hello world 3"
        MyLabel:
            text: "Hello world 4"   
'''
Builder.load_string(kv)

import kivy
kivy.require('1.7.1') # replace with your current kivy version !

from kivy.app import App
from kivy.uix.widget import Widget

class MyWidget(Widget):
    pass

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

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

To have font size depended on screen size, instead of using fixed values calculate it using self.heigh:

[MyLabel@Label]:
    text: ctx.text if hasattr(ctx, 'text') else ''
    font_size: self.height/2
    markup: True

UPDATE

Alternative approach is setting variable using #:set syntax:

kv = '''
#:set default_font_size "36sp"
<MyWidget>:
    id: f_wid
    BoxLayout:
        size: f_wid.size
        orientation: 'vertical'
        Label:
            text: "Hello world 1"
            font_size: default_font_size
        Label:
            text: "Hello world 2"
            font_size: default_font_size
        Label:
            text: "Hello world 3"
            font_size: default_font_size
        Label:
            text: "Hello world 4"   
            font_size: default_font_size
        Label:
            text: "Hello world 1"
            font_size: default_font_size
        Label:
            text: "Hello world 2"
            font_size: default_font_size
        Label:
            text: "Hello world 3"
            font_size: default_font_size
        Label:
            text: "Hello world 4"   
            font_size: default_font_size
'''
Builder.load_string(kv)

i already add some txt files in android by this path /data/data/package-name/files/app/filefolder/file.txt

the txt file is in the same directory with main.py like /same_directory_with_main.py/filefolder/file.txt

based on this experience, i am trying to add some custom fonts in my application.
and i makes directory exactly same way which add txt files.

part of main.py

from kivy.config import Config      
Config.set('kivy', 'default_font', [
    '/data/data/org.test.tubuc/files/app/font/NanumSquareR.ttfs',
    '/data/data/org.test.tubuc/files/app/font/NanumSquareL.ttfs',
])

but logcat says can’t find the font path.
here the log.

09-24 10:47:57.506 18392 18581 I python  : ('Android kivy bootstrap done. __name__ is', '__main__')
09-24 10:47:57.540 18392 18581 I python  : ['/data/user/0/org.test.tubuc/files/app/lib/python2.7/site-packages', '/data/user/0/org.test.tubuc/files/app/lib/site-python']
09-24 10:47:57.540 18392 18581 I python  : AND: Ran string
09-24 10:47:57.540 18392 18581 I python  : Run user program, change dir and execute entrypoint
09-24 10:47:57.650 18392 18581 I python  : [WARNING] [Config      ] Older configuration version detected (0 instead of 19)
09-24 10:47:57.650 18392 18581 I python  : [WARNING] [Config      ] Upgrading configuration in progress.
09-24 10:47:57.659 18392 18581 I python  : [INFO   ] [Logger      ] Record log in /data/user/0/org.test.tubuc/files/app/.kivy/logs/kivy_18-09-24_0.txt
09-24 10:47:57.659 18392 18581 I python  : [INFO   ] [Kivy        ] v1.10.0
09-24 10:47:57.660 18392 18581 I python  : [INFO   ] [Python      ] v2.7.2 (default, Aug 17 2018, 08:01:29) 
09-24 10:47:57.660 18392 18581 I python  : [GCC 4.9.x 20150123 (prerelease)]
09-24 10:47:57.691 18392 18581 I python  : [INFO   ] [Factory     ] 194 symbols loaded
09-24 10:47:57.994 18392 18581 I python  : [INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_gif (img_pil, img_ffpyplayer ignored)
09-24 10:47:58.022 18392 18581 I python  : [INFO   ] [Text        ] Provider: sdl2
09-24 10:47:58.023 18392 18581 I python  :  Traceback (most recent call last):
09-24 10:47:58.023 18392 18581 I python  :    File "/root/Desktop/hi/.buildozer/android/app/main.py", line 14, in <module>
09-24 10:47:58.024 18392 18581 I python  :    File "/root/Desktop/hi/.buildozer/android/platform/build/dists/tubuc/private/lib/python2.7/site-packages/kivy/uix/button.py", line 40, in <module>
09-24 10:47:58.024 18392 18581 I python  :    File "/root/Desktop/hi/.buildozer/android/platform/build/dists/tubuc/private/lib/python2.7/site-packages/kivy/uix/label.py", line 246, in <module>
09-24 10:47:58.024 18392 18581 I python  :    File "/root/Desktop/hi/.buildozer/android/platform/build/dists/tubuc/private/lib/python2.7/site-packages/kivy/core/text/__init__.py", line 797, in <module>
09-24 10:47:58.025 18392 18581 I python  :    File "/root/Desktop/hi/.buildozer/android/platform/build/dists/tubuc/private/lib/python2.7/site-packages/kivy/core/text/__init__.py", line 248, in register
09-24 10:47:58.025 18392 18581 I python  :  IOError: File /data/data/org.test.tubuc/files/app/font/NanumSquareL.ttfs not found
09-24 10:47:58.042 18392 18581 I python  : Python for android ended.

How can i add a font to android? thank you.

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

sdayu opened this issue

Apr 16, 2019

· 15 comments


Closed

Can KivyMD change font family?

#35

sdayu opened this issue

Apr 16, 2019

· 15 comments

Comments

@sdayu

I use KivyMD to display other languages using a special character not limited to roman, but the program did not display the character from other languages. In KIvy, I can add default font to the program, but KivyMD dit not display it. Is KivyMD support other fonts?

@HeaTTheatR

            MDLabel:
                text: '  Цитаты святых'
                bold: True
                font_size: '20sp'
                font_name: 'data/font/gothic.ttf'
                color: 0, 0, 0, 1

Снимок экрана 2019-04-16 в 16 28 38

@sdayu

@sdayu

It ok for Label, could you check in other widgets like MDFillRoundFlatButton. Thank you.

@sdayu

This is my result

                MDFillRoundFlatButton:
                    color: 0, 0, 0, 1
                    bold: True
                    font_size: '30sp'
                    font_name: 'fonts/THSarabunNew.ttf'
                    text: 'Xลืมรหัสผ่านX

Screenshot from 2019-04-16 21-10-15

@HeaTTheatR

@sdayu

                Button:
                    color: 0, 0, 0, 1
                    bold: True
                    font_size: '30sp'
                    font_name: 'fonts/THSarabunNew.ttf'
                    text: 'Xลืมรหัสผ่านX

Show result now…

@sdayu

The upper button is resulting Kivy Button, and the bottom is resulting form KivyMD.
Screenshot from 2019-04-17 09-22-04

@HeaTTheatR

@sdayu

                Button:
                    text: 'Xลืมรหัสผ่านX

Снимок экрана 2019-04-17 в 10 38 25

@sdayu

@kentang2017

one more question, is it possible to use non-english font as title on toolbar?

@HeaTTheatR

@senchoi

@kentang2017 Try

MDToolbar title doesn’t seem to use font_name. It doesn’t work.

@senchoi

one more question, is it possible to use non-english font as title on toolbar?

Did you manage to use non-english font?
I’m still having a hard time making the title Korean.

@quadrismegistus

@senchoi and @kentang2017, I was able to change font options in the title label by accessing the ‘label_title’ id (I had to dig into the code to find how KivyMD calls the toolbar). In my MainApp(App):

def build(self):
    global app,root
    app = self
    self.root = root = Builder.load_file('main.kv')
    
    # edit logo
    logo=root.ids.toolbar.ids.label_title
    logo.font_name='assets/Strengthen.ttf'
    logo.font_size='58dp'
    logo.pos_hint={'center_y':0.43}

@CristianCala

@guru-sai-shreesh

Thanks dude you saved me😌

In the previous part we left off with a basic Kivy app that displays a label. In this part we’re going to talk about label properties.

But before we delve into the topic, here’s some info for you.

*****

Book Info

I just published my Kivy book, GUI Programming with Python and Kivy. It’s pretty long (over 800 pages) and comprehensive. And, which also counts, easy to read. The book contains lots of illustrations.

This book covers all the basics that you need to know to start programming GUI applications with Python and Kivy. Throughout the book we are building a GUI application from scratch, a fully functional game using all kinds of tools that Kivy has to offer. It’s our Slugrace project, but covered in a much more in-depth manner.

Each part of the book starts with a theoretical introduction of a topic or idea that we then implement in the project. I assume you have no prior knowledge of the Kivy library, but you should have at least some basic knowledge of the Python programming language, including the object-oriented programming paradigm as this is what we will be using a lot in this book.

Kivy book

The book covers all the basic elements of Kivy that you have to know, like widgets, layouts, Kivy ids and properties, graphics, screens, animation, sound. Finally we’ll deploy the app to Windows. It is pretty comprehensive and after you finish it, I’m sure you’ll be able to create your own awesome GUI apps of any kind, not just games.

I hope you will have at least as much fun reading the book as I had writing it.

As far as this Kivy series is concerned, the following parts will contain the most important elements covered in the book. However, some elements will be presented in a simplified way here on my blog or omitted completely.

____________

If you are interested, you can purchase the book in four versions. Here are the links:

1) ebook – pdf version on my website – in full color

Here you can see the description of the book, sample graphics from the book and the full table of contents.

2) ebook – Kindle version on Amazon – in full color

3) paperback version on Amazon – in black and white

4) paperback version on Amazon – in full color

*****

And Now Let’s Move On…

Here’s the code again.

The Python file:

# File name: main.py

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

class HelloWorldApp(App):
    def build(self):
        return Label()

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

and the kv file:

# File name: helloworld.kv

<Label>:
    text: 'Hello World!'

This program displays a label. The label has a text property. This is a special Kivy property, not to be confused with the regular Python property. We’re going to use Kivy properties a lot, and even create our own ones, just bear with me. Anyway, the Label class has some more properties. We’re going to have a look at the Label properties in this part and then in the next part we’ll see how to use other widgets like buttons, toggle buttons, check boxes, text inputs and sliders, both in Python and in the Kivy language. These are the widgets we’ll be making use of in our project, but there many others, which you can look up in the documentation, which you can find at kivy.org.

And now let’s have a closer look at the Label class and the Label properties. You already know the text property. It’s used to set the actual text you want to display. By the way, you probably noticed that the name of a property is followed by a colon and then comes the value we want to set the property to. This same syntax is valid for all the other properties.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Other Label Properties – The font_size Property

The next property I’d like to mention is font_size. The name is pretty self-explanatory, let me just add that the value is in pixels. Let’s add this property to the code in our helloworld.kv file:

<Label>:
    text: 'Hello World!'
    font_size: 50

If you now run the program (you must go to the main.py tab first), the label displayed in the window will be much bigger than before:

label properties - app running with font_size property set

Other Label Properties – The color Property

There’s another property for the color of the
text, called color to make things more interesting. What is
really interesting about this property, however, is its value, which is a list
with four elements: r(ed), g(reen), b(lue) and a(lpha). The default value is
[1, 1, 1, 1], which corresponds to fully opaque white. The values for each
component are in the range from 0 to 1, which probably is not exactly what you
are used to. In a lot of frameworks the values of r, g, b and a are from 0 to
255. Here, it is your task to recalculate the values so that they fit in the
0-1 range. Just keep in mind that 0 is the same in both ranges and 255 in the
traditional scale corresponds to 1 in kv. So, if you want the color to be a
shade of purple where the values are:

r = 126

g = 45

b = 210

a = 255

you can either calculate the kv values manually
like so:

r = 126/255 ≈ 0.56

g = 45/255 ≈ 0.18

b = 210/255 ≈ 0.82

a = 255/255 = 1

or type the operations directly in the list. So, in our case you could set the color like so:

color: [.56, .18, .82, 1]

or like so:

color: [126/255, 45/255, 210/255, 1]

You can use whichever you like. I like the second one better because I’m used to the 0-255 range, but I’m going to use them interchangeably throughout the project so that you get used to both of them. Now the full kv code is:

<Label>:    
    text: 'Hello World!'
    font_size: 50
    color: [126/255, 45/255, 210/255, 1]

and if you run the program (from main.py), this is what you will get:

app running with color property set

Text Markup

There are lots of other properties that you can
use with the Label class. Some of them will be used in the project and I’ll
talk a little more about them when you need them. There is however one very
interesting property that we are not going to use in the app, and which is
definitely worth mentioning, that’s why I’d like to tell you something about it
now.

You can style your text using text markup. This is very similar to what you may be familiar with if you know some HTML, however instead of angled brackets (<>, </>) we use square brackets in kv ([ ], [/]). Just like in HTML there’s an opening tag and a closing tag, as you can see.

tags

There are lots of tags available. Let’s have a
look at just a small selection:

[b][/b] –  bold text

[i][/i] –  italic
text

[u][/u] –  underlined
text

[s][/s] –  strikethrough text

[sub][/sub] –  subscript
text

[sup][/sup] –  superscript
text

[size=<integer>][/size] –  font size

[color=#<color>][/color] –  text color

The markup Property

In order to use text markup, you must add one more property, markup, and set it to True. Let’s now change the text to something longer than Hello World and try the markup tags out. Here’s the code:

<Label>:    
    text: 'normal [b]bold[/b] [i]italic[/i] n[u]underlined[/u] [s]strikethrough[/s] n[sub]subscript[/sub] [sup]superscript[/sup] [size=100]big[/size] [color=#ff0f]yellow[/color]'
    font_size: 50
    color: [126/255, 45/255, 210/255, 1]
    markup: True

Two things to keep in mind:

First, the value of the text property, which is the string, should be
all on a single line.

Second, in text markup we use hex values for
colors, so if the rgba for yellow is 255, 255, 0, 255 (fully opaque), then its
hexadecimal representation is ff0f,
which you can see in the color tag.

Also notice that there are newline characters (n) inside the string.

Now run the program and you should get something like this:

text markup in action

We’ve been working with just one basic widget so far, the label. But there are lots of other useful widgets, like buttons, toggle buttons, check boxes, text inputs, sliders and many, many more. We’re going to use some of them in our application, so in the following parts I’ll show you some of the widgets that we’re going to use and some of their most important properties.

Как киви поддерживает китайский

1. Пусть каждый компонент задает китайский шрифт (font_name)

  • Найти шрифты через kivy.resources.resource_find
  • Зарегистрируйте шрифты через Label или LabelBase и т. Д.
# !/usr/bin/python
# -*-coding:utf-8-*-

import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.core.window import Window
from kivy.core.text import LabelBase
from kivy.config import Config

Config.write()


# # Загрузка ресурсов шрифта
kivy.resources.resource_add_path("./container_kvs")
font1 = kivy.resources.resource_find("msgothic.ttc")
#
 # #Via labelBase
LabelBase.register("msgothic_labelBase","msgothic2.ttc")
kivy.core.text.Label.register("msgothic_label","msgothic2.ttc")



class MyApp(App):

    def build(self):
        Window.fullscreen = 1
        layout = GridLayout(cols=2,spacing=2);
                 layout.add_widget (Button (text = "Шрифт кнопки по умолчанию"))
                 layout.add_widget (Label (text = "label-default font"))
                 layout.add_widget (Button (text = "Указать определенный шрифт", font_name = font1))
                 layout.add_widget (Label (text = "Указать определенный шрифт", font_name = font1))
                 layout.add_widget (Label (text = "Find font", font_name = "msgothic.ttc", outline_color = '# 666666')) # Если вы не укажете суффикс, он автоматически найдет шрифт в формате ttf по умолчанию
                 layout.add_widget (Button (text = "Найти шрифт 2", font_name = "msgothic2.ttc", markup = True))
                 layout.add_widget (Label (text = "метка зарегистрированного шрифта", font_name = "msgothic_label")) # обозначение псевдонима
                 layout.add_widget (Button (text = "зарегистрированный шрифт labelBase", font_name = "msgothic_labelBase")) # обозначение псевдонима
        return layout

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

Эффект: (Часть текста не может быть отображена из-за выбранного шрифта)

2. Измените конфигурацию по умолчанию [действительно для всех приложений]

  # Если вы не пишете конфигурацию сверху, вы можете запустить второй раз, чтобы увидеть эффект

from kivy.config import Config

Config.set('kivy', 'default_font', [
    'msgothic',
    'fonts/txb2.ttf'])
 # Config.write () # В этом предложении настройки будут обновлены до файла глобальной конфигурации


import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.core.window import Window
from kivy.core.text import LabelBase
from kivy.config import Config



 # # Загрузка ресурсов шрифта
kivy.resources.resource_add_path("./container_kvs")
font1 = kivy.resources.resource_find("msgothic.ttc")
#
 # #Via labelBase
LabelBase.register("msgothic_labelBase","msgothic2.ttc")
kivy.core.text.Label.register("msgothic_label","msgothic2.ttc")



class MyApp(App):

    def build(self):
        Window.fullscreen = 1
        layout = GridLayout(cols=2,spacing=2);
                 layout.add_widget (Button (text = "Шрифт кнопки по умолчанию"))
                 layout.add_widget (Label (text = "label-default font"))
                 layout.add_widget (Button (text = "Указать определенный шрифт", font_name = font1))
                 layout.add_widget (Label (text = "Указать определенный шрифт", font_name = font1))
                 layout.add_widget (Label (text = "Find font", font_name = "msgothic.ttc", outline_color = '# 666666')) # Если вы не укажете суффикс, он автоматически найдет шрифт в формате ttf по умолчанию
                 layout.add_widget (Button (text = "Найти шрифт 2", font_name = "msgothic2.ttc", markup = True))
                 layout.add_widget (Label (text = "метка зарегистрированного шрифта", font_name = "msgothic_label")) # обозначение псевдонима
                 layout.add_widget (Button (text = "зарегистрированный шрифт labelBase", font_name = "msgothic_labelBase")) # обозначение псевдонима
        return layout

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

эффект:

Примечание. Если вы добавите Config.writer ();, это повлияет на все приложения, связанные с kivy, и может привести к сбою некоторых из них со следующей ошибкой;

 OSError: File fonts/txb2.ttf not found

  • Решение первое: сбросьте шрифт по умолчанию

  • Решение 2. Восстановите конфигурацию по умолчанию, то есть удалите файл конфигурации kivy [config.ini] или измените исходную конфигурацию по умолчанию;

Расположение файла конфигурации KIVY под окном

C: Users Текущий пользователь .kivy config.ini

Конфигурация шрифта по умолчанию

default_font = [‘Roboto’, ‘data/fonts/Roboto-Regular.ttf’, ‘data/fonts/Roboto-Italic.ttf’, ‘data/fonts/Roboto-Bold.ttf’, ‘data/fonts/Roboto-BoldItalic.ttf’]

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить шрифт java swing
  • Как изменить шрифт flutter
  • Как изменить шрифт cambria math на times new roman
  • Как изменить шрифт blogger
  • Как изменить шрифт bdo

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии