我想通过 StringProperty 获取 TextInput 的文本,但它不起作用.我得到一个空字符串.在第二个示例中,我将整个 TextInput 声明为 ObjectProperty,然后它就可以工作了.我的第一个例子有什么问题?
I would like to get the text of my TextInput via a StringProperty, but it does not work. I get an empty string. In the second example, I am declaring the whole TextInput as an ObjectProperty and then it does work. What is wrong with my first example?
第一个示例不打印 TextInput 的文本例子1.py
from kivy.app import App
from kivy.base import Builder
from kivy.properties import StringProperty
from kivy.uix.boxlayout import BoxLayout
Builder.load_string("""
<rootwi>:
orientation: 'vertical'
Button:
on_press: root.print_txt()
TextInput:
text: root.textinputtext
""")
class rootwi(BoxLayout):
textinputtext = StringProperty()
def print_txt(self):
print(self.textinputtext)
class MyApp(App):
def build(self):
return rootwi()
if __name__ == '__main__':
MyApp().run()
第二个示例打印 TextInput 的文本,但使用 ObjectProperty 而不是 StringProperty example2.py
Second example does print text of TextInput, but uses a ObjectProperty not StringProperty example2.py
from kivy.app import App
from kivy.base import Builder
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
Builder.load_string("""
<rootwi>:
txt: txt
orientation: 'vertical'
Button:
on_press: root.print_txt()
TextInput:
id: txt
""")
class rootwi(BoxLayout):
txt = ObjectProperty()
def print_txt(self):
print(self.txt.text)
class MyApp(App):
def build(self):
return rootwi()
if __name__ == '__main__':
MyApp().run()
如果我将文本设置为特定的,它会显示在 TextInput 中.(但仍然无法打印)
from kivy.app import App
from kivy.base import Builder
from kivy.properties import StringProperty
from kivy.uix.boxlayout import BoxLayout
Builder.load_string("""
<rootwi>:
orientation: 'vertical'
Button:
on_press: root.print_txt()
TextInput:
text: root.textinputtext
""")
class rootwi(BoxLayout):
textinputtext = StringProperty()
def __init__(self, **kwargs):
self.textinputtext = 'palim'
super(rootwi, self).__init__(**kwargs)
def print_txt(self):
print(self.textinputtext)
class MyApp(App):
def build(self):
return rootwi()
if __name__ == '__main__':
MyApp().run()
如果你想使用 StringProperty 设置和获取文本,那么你应该创建一个双向绑定:
If you want set and get the text using the StringProperty then you should create a bidirectional bind:
from kivy.app import App
from kivy.base import Builder
from kivy.properties import StringProperty, ObjectProperty
from kivy.uix.boxlayout import BoxLayout
Builder.load_string("""
<rootwi>:
orientation: 'vertical'
textinputtext: txt.text
Button:
on_press: root.print_txt()
TextInput:
id: txt
text: root.textinputtext
""")
class rootwi(BoxLayout):
textinputtext = StringProperty()
def __init__(self, **kwargs):
super(rootwi, self).__init__(**kwargs)
self.textinputtext = 'palim'
def print_txt(self):
print(self.textinputtext)
class MyApp(App):
def build(self):
return rootwi()
if __name__ == '__main__':
MyApp().run()
输出:
这篇关于StringProperty 的 TextInput 的 kivy 参考文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!