Kivy文本标记打印自己的语法

时间:2016-04-21 14:18:24

标签: python kivy kivy-language

我正在测试Kivy的标记功能。我的测试程序的基本轮廓是有4个标签和一个按钮,如果按下按钮,,它会改变标签文本的第一个字母的颜色。现在,问题是当我第一次按下按钮时,它会从第二次按下时改变所有标签文本的第一个字母的颜色,然后开始在文本开头以相反的方式添加标记语法。这是该计划:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.lang import Builder
import string

Builder.load_string(
'''
<CLabel@Label>:
    markup: True

<box>:
    orientation: 'vertical'

    Button:
        text: 'press'
        on_press: app.change()


    CLabel:
        id: a
        text: 'abcd'

    CLabel:
        id: b
        text: 'efgh'

    CLabel:
        id: c
        text: 'ijkl'

    CLabel:
        id: d
        text: 'mnop'
'''
)

class box(BoxLayout):
    pass

class main(App):
    def change(self):
        for lol in string.lowercase[:4]:
            self.root.ids[lol].text = '[color=#E5D209]{}[/color]{}'.format(self.root.ids[lol].text[0], self.root.ids[lol].text[1:])

    def build(self):
        return box()

if __name__ == "__main__":
    main().run()

这是第一次按下后的输出: enter image description here

这是第二次按下后的输出: enter image description here

这是第三次出版后的输出: enter image description here

我希望你现在能解决问题。文本开头的标记语法随着按下按钮的次数而不断增加。

我想也许是循环的错。所以我删除了循环并仅使用第一个小部件进行了测试。同样的问题。

现在这里有一个问题 - 我通过更改改变函数的内容来改变颜色,如下所示:

def change(self):
    self.root.ids.a.text = '[color=#E5D209]a[/color]bcd'
    self.root.ids.b.text = '[color=#E5D209]e[/color]fgh'
    self.root.ids.c.text = '[color=#E5D209]i[/color]jkl'
    self.root.ids.d.text = '[color=#E5D209]m[/color]nop'

它完美无缺。但通过这种方法,我将不得不复制粘贴很多行。这只是我正在研究的一小部分。我正在研究的真实项目有超过15个标签,每个标签的复制粘贴都很烦人。如果通过循环完成它会好得多。它使工作变得简短而精确。

在此之后,出于挫败感,我尝试使用此代码的get_color_from_hex方法:

self.root.ids[lol].text[0] = self.root.ids[lol].text[0].get_color_from_hex('#E5D209')

但我最终收到一条错误消息:

AttributeError: 'str' object has no attribute 'color'
如果有人想方设法改变上帝文字第一个字母的颜色知道有多少标签,我真的很高兴。 :'(

1 个答案:

答案 0 :(得分:1)

标记是存储在text中的字符串的一部分。所以第二次运行循环时,第一个字符([)会插入标记标记之间,搞乱解析。

您可以通过将原始文本存储在另一个StringProperty中来实现您想要做的事情,我们称之为_hidden_text。然后,在循环中,您可以设置

self.root.ids[lol].text = '[color=#E5D209]{}[/color]{}'.format(self.root.ids[lol]._hidden_text[0], self.root.ids[lol]._hidden_text[1:])

这样可以避免重复使用添加的标记。 当然,您可能需要设置绑定以自动执行作业_hidden_texttext

编辑:

添加此类定义:

class CLabel(Label):
    hidden_text = StringProperty('')

然后将CLabel的kv样式更改为

<CLabel>:
    markup: True
    text: self.hidden_text

CLabel的每次使用都应该是

CLabel:
    id: a
    hidden_text: 'abcd'