首页 > 解决方案 > Kivy:如何更改模板中 TextInput 的 text_hint 值

问题描述

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

<InformationBox@FloatLayout>
    lblTxtIn: 'Unknown Variable Name'
    txtInHint: "..."
    Label:
        text: root.lblTxtIn
        color: 235/255, 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, 0, 0, 1
<MainMenu>:
    InformationBox:
        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)

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

标签: pythonkivykivy-language

解决方案


您可以使用以下方法来更新 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, 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, 0, 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()

推荐阅读