由StringProperty提供TextInput的kivy引用文本

时间:2017-06-19 12:43:50

标签: python python-3.x kivy kivy-language

我想通过StringProperty获取TextInput的文本,但它不起作用。我得到一个空字符串。在第二个示例中,我将整个TextInput声明为ObjectProperty然后它确实有效。我的第一个例子出了什么问题?

如何使用StringProperty定义TextInput中的文本?

第一个示例不打印TextInput 的文本 example1.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

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

1 个答案:

答案 0 :(得分:2)

如果你想使用StringProperty设置并获取文本,那么你应该创建一个双向绑定:

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

<强>输出:

enter image description here