Как динамически изменить размер шрифта в текстовой разметке? - PullRequest
1 голос
/ 21 июня 2019

Я хочу динамически изменить размер шрифта в Text Markup: https://kivy.org/doc/stable/api-kivy.core.text.markup.html

Код ниже работает хорошо.

str_ = "[size=17sp]" + 'TEST' + "[/size]"

Код ниже не работает хорошо.

from kivy.metrics import sp
font_size = sp(17)
str_ = "[size=font_size]" + 'TEST' + "[/size]"

Как мне изменить это?или это невозможно сделать с помощью Text Markup?

Ответы [ 2 ]

1 голос
/ 21 июня 2019

Существует три возможных решения проблемы, и они следующие:

Фрагменты

Метод 1 - разделенная разметка

from kivy.core.text.markup import MarkupLabel

        markup_splitted = MarkupLabel(self.ids.label.text).markup

        font_size = '50sp'
        self.ids.label.text = ''

        for item in markup_splitted:
            if item[:6] == '[size=':
                self.ids.label.text += f'[size={font_size}]'
            else:
                self.ids.label.text += item

Метод 2 - целочисленное значение безsp

font_size = 17
str_ = f"[size={font_size}]" + 'TEST' + "[/size]"

Метод 3 - строковое значение с sp

font_size = '17sp'
str_ = f"[size={font_size}]" + 'TEST' + "[/size]"

Пример

Ниже показаны три метода решения проблемы.

main.py

from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
from kivy.properties import StringProperty
from kivy.core.text.markup import MarkupLabel


class MarkupTextFontSize(Screen):
    txt = StringProperty('')

    def __init__(self, **kwargs):
        super(MarkupTextFontSize, self).__init__(**kwargs)
        self.txt = '[color=ff3333]Unselectable [size=20]item[/size][/color][anchor=a]a\nChars [anchor=b]b\n[ref=myref]ref[/ref]'
        # self.txt += "[anchor=title1][size=24]This is my Big title.[/size][anchor=content] Hello world"

    def change_font_size(self):
        self.ids.label.font_size = '50sp'

        # Method 1 - split markup
        markup_splitted = MarkupLabel(self.ids.label4.text).markup

        font_size = '50sp'
        self.ids.label4.text = ''

        for item in markup_splitted:
            if item[:6] == '[size=':
                self.ids.label4.text += f'[size={font_size}]'
            else:
                self.ids.label4.text += item

        # Method 2 - using integer value
        font_size = 17
        self.ids.label2.text = f"[size={font_size}]" + 'TEST' + "[/size]"

        # Method 3 - using string value
        font_size = '30sp'
        self.ids.label3.text = f"[anchor=title1][size={font_size}]This is my Big title.[/size][anchor=content] Hello world"


runTouchApp(Builder.load_string("""
MarkupTextFontSize:

<MarkupTextFontSize>:
    BoxLayout:
        orientation: 'vertical'

        Button:
            id: btn
            text: 'Change FontSize'
            size_hint: 1, 0.2
            markup: True
            on_release: root.change_font_size()
        Label:
            id: label
            text: root.txt
            markup: True
        Label:
            id: label2
            text: '[color=ff3333]Unselectable [size=20sp]item[/size][/color]'
            markup: True
        Label:
            id: label3
            text: "[anchor=title1][size=24]This is my Big title.[/size][anchor=content] Hello world"
            markup: True
        Label:
            id: label4
            text: "[anchor=title1][size=24]This is my Big title.[/size][anchor=content] Hello world"
            markup: True
"""))

Выход

Before font size changes After font size changes

0 голосов
/ 21 июня 2019

Попробуйте интерполировать строки следующим образом:

from kivy.metrics import sp
font_size = sp(17)
str_ = f'[size={font_size}]' + 'TEST' + "[/size]"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...