Kivy:如何更改模板中TextInput的文本提示值

2024-10-02 00:36:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过更改TextInput的text\u 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\u 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)

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


Tags: textfromimportselfdefcustomchangeclass
1条回答
网友
1楼 · 发布于 2024-10-02 00:36:01

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

相关问题 更多 >

    热门问题