0

我刚开始学习 Python Kivy,想从控制台中的 TextInput 错误输出文本:AttributeError: 'kivy.properties.ObjectProperty' object has no attribute text

我的 Python 代码:

class SearchField(AnchorLayout):
    search_field = ObjectProperty(None)
    result = search_field.text
class MyApp(App):
    def build(self):
        return SearchField()
if __name__ == "__main__":
    MyApp().run()

我的 .kv 代码:

<SearchField>
    search_field: search_field
    anchor_x: "center"
    anchor_y: 'top'
    padding: (0, 20)
    BoxLayout:
        size_hint: (None, None)
        size: (600, 30)
        TextInput:
            id: search_field
            multiline: False
        Button:
            size_hint: (None, None)
            size: (50, 30)
            text: "Search"
            on_release: search_result.text = root.result
    Label:
         id: search_result
         text: ""
         font_size: 30
4

1 回答 1

0

这个程序有几个错误。1-text属性在声明为 ObjectProperty 之后直接应用于 search_field 变量。所以,它是一个 ObjectProperty 实例并且没有属性text。2-程序的缩进做得不好。3- .kv 文件中没有很好地声明属性。

虽然我还没有完全理解程序的目的,但这里有一个安全的版本:

from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.properties import ObjectProperty


class SearchField(AnchorLayout):
    search_field = ObjectProperty(None)
    result = ""

    def btn(self):
        self.result = self.search_field.text
        print(self.result)


class TestApp(App):
    def build(self):
        return SearchField()


if __name__ == "__main__":
    TestApp().run()

这是kv文件:

<SearchField>
    search_field: search_field
    anchor_x: "center"
    anchor_y: 'top'
    padding: (0, 20)
    search_result: search_result
    search_field: search_field
    BoxLayout:
        size_hint: (None, None)
        size: (600, 30)
        TextInput:
            id: search_field
            multiline: False
        Button:
            size_hint: (None, None)
            size: (50, 30)
            text: "Search"
            on_release: root.btn()
    Label:
        id: search_result
        text: ""
        font_size: 30
于 2020-08-27T17:51:32.813 回答