【问题标题】:KIVY python - change TextInput colorKIVY python - 更改 TextInput 颜色
【发布时间】:2017-10-14 14:08:33
【问题描述】:

当用户修改 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)

【问题讨论】:

    标签: kivy textinput


    【解决方案1】:

    给你

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

    【讨论】:

      【解决方案2】:

      您将一个方法添加到您的根小部件 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)
      

      输出

      【讨论】:

        【解决方案3】:

        更改文本颜色的最简单方法是使用 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)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-03-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-27
          • 1970-01-01
          相关资源
          最近更新 更多