KIVY python - 更改TextInput颜色

时间:2017-10-14 14:08:33

标签: kivy textinput

我希望在用户修改TextInput时更改TextInput中包含的文本的颜色。 例如:

  • 有一个文字输入,预先写好'
  • 中的文字
  • 如果您修改此文字的字符,其颜色会立即变为红色

debug2.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder



class MyDebug(BoxLayout):
    def __init__(self, **kwargs):
        super(MyDebug, self).__init__(**kwargs)

Builder.load_file("debug2.kv")

class MyAppli(App):

    def build(self):
        return MyDebug()

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

debug2.kv

#:kivy 1.9.1

<MyDebug>:

    TextInput:
        text: "Edit me !" # change color to (1, 0, 0, 1) when modified
        foreground_color: (0.3, 0.4, 0.5, 1)

3 个答案:

答案 0 :(得分:0)

你去吧

吡啶:

class ColorTextInput(TextInput):

    def changetored(self):
        if self.text != "Edit me !":
            self.foreground_color = (1,0,0,1)

KV:

ColorTextInput:
    text: "Edit me !" # change color to (1, 0, 0, 1) when modified
    on_text: self.changetored()

答案 1 :(得分:0)

您可以在根小部件MyDebug中添加一个方法,并将一个事件on_text添加到您的kv文件中,如下所示:

片段

debug2.py

class MyDebug(BoxLayout):
    def __init__(self, **kwargs):
        super(MyDebug, self).__init__(**kwargs)

    def on_text_change(self, instance, value):
        instance.foreground_color = (1, 0, 0, 1)

debug2.kv

<MyDebug>:
    TextInput:
        text: "Edit me !" # change color to (1, 0, 0, 1) when modified
        foreground_color: (0.3, 0.4, 0.5, 1)
        on_text: root.on_text_change(self, self.text)

输出

OnText Change ForegroundColor

答案 2 :(得分:0)

更改文本颜色的最简单方法是使用on_text

TextInput:
    text: 'Color will change from black to red if text is modified'
    on_text: self.foreground_color = (1,0,0,1)##red
    foreground_color = (0,0,0,1)