簡體   English   中英

我如何從 python 訪問在.kv 文件中創建的文本輸入

[英]how do i access textinputs created in .kv file from python

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 中寫了一些東西,它也總是返回空白

您的示例存在一些問題,其中之一是它在示例屏幕頂部添加了一個空白屏幕,因此什么都看不到。 除此之外,沒有辦法嘗試從您的 kv 訪問TextInput
無論如何,如果您添加一個on_text事件,您可以檢查輸入的內容。

一種方法是首先在您的app class 中添加回調:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM