简体   繁体   中英

Python Kivy error: 'kivy.properties.ObjectProperty' object has no attribute text

I've just started to learn Python Kivy and want to output text from TextInput Error in console: AttributeError: 'kivy.properties.ObjectProperty' object has no attribute text

My Python Code:

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

My.kv code:

<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

Several errors are made in this program. 1- the text attribute is applied to the search_field variable directly after its declaration as ObjectProperty. So, it's an ObjectProperty instance and dont have the attribute text . 2- The indentation of the program is badly done. 3- The properties are not well declared in the.kv file.

Although I haven't fully understood the purpose of the program, here is a safe version:

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

And here is the kv file:

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM