Kivy:如何更改模板中TextInput的text_hint值

问题描述

我试图通过更改TextInput的text_hint值来显示一些数据。如果我打印的值是正确的,但是我无法在屏幕上更新它们。这是我在.kv文件中声明和使用模板的方式。

<@R_394_4045@ionBox@FloatLayout>
    lblTxtIn: 'UnkNown Variable Name'
    txtInHint: "..."
    Label:
        text: root.lblTxtIn
        color: 235/255,235/255,1
        pos_hint: {'center_x': 0.5,'center_y': 0.7}
        bold: True
    TextInput:
        readonly: True
        hint_text: root.txtInHint
        multiline: False
        pos_hint: {'center_x': 0.5,'center_y': 0.4}
        size_hint: (0.3,0.25)
        hint_text_color: 0,1
<MainMenu>:
    @R_394_4045@ionBox:
        id: mylabel
        lblTxtIn: "Data Type Name"
        txtInHint: root.custom

这是我尝试更改python中的值的方法

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.clock import Clock
from kivy.properties import ObjectProperty,StringProperty
import random


class MainMenu(FloatLayout):
    custom = "0"


class MyMainApp(App):
    def build(self):
        return MainMenu()

    def txt_change(self,*args):
        MainMenu.custom = str(random.randrange(1,10))
        print(MainMenu.custom)

    Clock.schedule_interval(txt_change,1)

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

我还尝试使用ObjectProperty对其进行更改,尽管随后它显示错误消息,表明该对象没有'text_hint'属性

class MainMenu(FloatLayout):
    mylabel = Objectproperty()

    def change_text(self,*args):
        MainMenu.mylabel.text_hint = "1"


class MyMainApp(App):
    def build(self):
        return MainMenu()

    Clock.schedule_interval(MainMenu.change_text,1)

我是一个初学者,不知道我是在做一个简单的错误还是应该以一种完全不同的方式来解决这个问题。如果有人可以帮助我,我会感到很高兴。

解决方法

您可以使用以下方法来更新textinput字段:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.clock import Clock
import random


APP_KV = """
FloatLayout:
    lblTxtIn: "Data Type Name"
    txtInHint: "..."
    Label:
        text: root.lblTxtIn
        color: 235/255,235/255,1
        pos_hint: {'center_x': 0.5,'center_y': 0.7}
        bold: True    
    TextInput:
        id: mytxtinput
        readonly: True
        hint_text: root.txtInHint
        multiline: False
        pos_hint: {'center_x': 0.5,'center_y': 0.4}
        size_hint: (0.3,0.25)
        hint_text_color: 0,1
"""

class MyMainApp(App):
    def build(self):
        return Builder.load_string(APP_KV)

    def txt_change(self,*args):
        app.root.ids.mytxtinput.hint_text = str(random.randrange(1,10))
        print(app.root.ids.mytxtinput.hint_text)

    Clock.schedule_interval(txt_change,1)

if __name__ == "__main__":
    app = MyMainApp()
    app.run()