【问题标题】:how do i access textinputs created in .kv file from python如何从 python 访问在 .kv 文件中创建的文本输入
【发布时间】:2020-05-13 23:25:09
【问题描述】:
with open("file.kv", encoding='utf-8') as f:
    Builder.load_string(f.read())
class content(Screen):
    pass
class resistor(Screen):
    pass
sm = ScreenManager()
sm.add_widget(content())
sm.add_widget(resistor())

def printthecontentsofthetextinput():
    do something

class MyApp(App):
    def build(self):
       return sm

这是我的 kv 文件:

<resistor>
name:"r"
Image:
    source:"lamp1.jpg"
    allow_stretch:True
    keep_ratio:False
    FloatLayout:
        size:root.width,root.height
        allow_stretch:False
        keep_ratio:False
        Label:
            text:"R"
            color:1,1,1,1
            pos_hint:{"x":0.03,"y":0.23}
            size_hint:0.1,0.05
        TextInput:
            id:rprim
            focus:True
            background_color:0.8,0.96,0.88,1
            pos_hint:{"x":0.15,"y":0.23}
            size_hint:0.1,0.05
        Label:
            text:"Ω"
            color:1,1,1,1
            pos_hint:{"x":0.28,"y":0.23}
            size_hint:0.05,0.05

我正在尝试使用 id 访问文本输入:rprim

我试过 print(resistor().ids.rprim.text) 但即使我在 textinput 中写了一些东西,它总是返回空白

【问题讨论】:

    标签: python user-interface kivy kivy-language


    【解决方案1】:

    您的示例存在一些问题,其中之一是它在示例屏幕顶部添加了一个空白屏幕,因此什么都看不到。 除此之外,没有办法尝试从您的 kv 访问 TextInput
    无论如何,如果您添加on_text 事件,您可以检查输入的内容。

    一种方法是首先在 app 类中添加回调:

    class MyApp(App):
        def build(self):
            return sm
    
        def on_text_input(self, text_input):
            print(text_input.text)
    

    ..然后将回调添加到TextInput:

                TextInput:
                    id:rprim
                    focus:True
                    background_color:0.8,0.96,0.88,1
                    pos_hint:{"x":0.15,"y":0.23}
                    size_hint:0.1,0.05
                    on_text: app.on_text_input(self)
    

    【讨论】:

    • “它在示例屏幕的顶部添加了一个空白屏幕,所以什么都看不见”,你能解释一下你的意思吗?谢谢。
    • 因为sm.add_widget(content()) 我看到了一个空的黑色窗口。这个屏幕(一个空的)是第一个屏幕。由于无法更改当前屏幕,我不得不注释掉这一行,所以我可以看到带有 TextInput 的屏幕...
    • @pythonier 如果你觉得我的回答对你有帮助,那么你可以考虑accept it,让其他人也看到它.. ;o)
    猜你喜欢
    • 1970-01-01
    • 2014-06-17
    • 2021-06-24
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    相关资源
    最近更新 更多