如何从 Python 访问在 .kv 文件中创建的文本输入


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 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)

最新更新