[英]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 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:我的 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()
My.kv code:我的.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
Several errors are made in this program.这个程序有几个错误。 1- the text
attribute is applied to the search_field variable directly after its declaration as ObjectProperty. 1- text
属性在声明为 ObjectProperty 之后直接应用于 search_field 变量。 So, it's an ObjectProperty instance and dont have the attribute text
.所以,它是一个 ObjectProperty 实例并且没有属性text
。 2- The indentation of the program is badly done. 2-程序的缩进做得不好。 3- The properties are not well declared in the.kv file. 3- 在.kv 文件中没有很好地声明属性。
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:这是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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.