Mike Delta
Mike Delta

Reputation: 808

KIVY python - change TextInput color

I want to change the color of text contained in the TextInput when it is modified by the user. Example:

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)

Upvotes: 2

Views: 9528

Answers (4)

Osmar Souza
Osmar Souza

Reputation: 1

You can use the example below:

TextInput:
    id: txt_add_data_trial
    multiline: True
    cursor_color: app.theme_cls.primary_color
    font_family: 'Roboto'
    font_size: '20sp'
    size_hint: 1, None
    height: '60dp'
    foreground_color: app.theme_cls.primary_color if self.focus==True else self.disabled_foreground_color
    background_normal: './assets/imgs/transparent.png'
    background_active: './assets/imgs/transparent.png'                            
    canvas.after:
        Color:
            group: "color"
            rgba: app.theme_cls.primary_color if self.focus==True else C('#d3d3d3')
        Line:
            group: "rectangle"
            width: dp(1.25)
            rectangle: (self.x, self.y, self.width, self.height)

Upvotes: 0

i.r.b.a
i.r.b.a

Reputation: 79

Easiest way to change the color of the text is to use 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)

Upvotes: 0

ikolim
ikolim

Reputation: 16021

You add a method into your root widget, MyDebug and an event, on_text into your kv file as follow:

Snippet

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)

Output

OnText Change ForegroundColor

Upvotes: 0

PalimPalim
PalimPalim

Reputation: 3048

Here you go

py:

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()

Upvotes: 2

Related Questions