“ AttributeError:'NoneType'对象没有属性'insert'”

时间:2019-12-09 19:35:33

标签: python kivy textfield

我真的很困惑为什么只有我的一个文本输入字段会发生这种情况。我有多个其他人的工作都很好,尽管我研究了类似的问题,但没有找到适合我情况的答案。我得到的错误是“ AttributeError:'NoneType'对象没有属性'insert'”

main.py

class PredictEstimate(Screen):
    children = ObjectProperty(None)

    def submitPatient(self):
        childrenText = self.children.text
        print("Children Text: ", childrenText)


class WindowManager(ScreenManager):
    pass

kv = Builder.load_file("login.kv")
sm = WindowManager()

screens = [PredictEstimate(name="predict")]
for screen in screens:
    sm.add_widget(screen)

class MyMainApp(App):
    def build(self):
        return sm

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

.kv文件

<PredictEstimate>:

    children: children


    FloatLayout:

        Label:
            text:"Number of Children: "
            font_size: (40)
            pos_hint: {"x":0.05, "y":0.45}
            size_hint: 0.4, 0.15

        TextInput:
            id: children
            font_size: (50)
            multiline: False
            pos_hint: {"x": 0.5, "y":0.45}
            size_hint: 0.4, 0.1

        Button:
            pos_hint:{"x":0.68, "y": 0.05}
            size_hint:0.3,0.1
            font_size: (50)
            background_color: .1, .1, .1, .1
            text: "Submit"
            on_release:
                root.submitPatient()

1 个答案:

答案 0 :(得分:2)

说明:

Widget类具有children属性,该属性用于存储小部件的子级,因此从Widget继承的任何类(例如Screen和PredictEstimate)都将拥有该类,但是您将其覆盖为None并生成错误您指出的。

解决方案:

请勿使用子代,而是使用该属性的另一个名称:

main.py

from kivy.app import App

from kivy.lang.builder import Builder
from kivy.properties import ObjectProperty
from kivy.uix.screenmanager import ScreenManager, Screen


class PredictEstimate(Screen):
    text_input = ObjectProperty(None)

    def submitPatient(self):
        childrenText = self.text_input.text
        print("Children Text: ", childrenText)


class WindowManager(ScreenManager):
    pass


kv = Builder.load_file("login.kv")
sm = WindowManager()

screens = [PredictEstimate(name="predict")]
for screen in screens:
    sm.add_widget(screen)


class MyMainApp(App):
    def build(self):
        return sm


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

login.kv

<PredictEstimate>:
    text_input: text_input

    FloatLayout:
        Label:
            text:"Number of Children: "
            font_size: (40)
            pos_hint: {"x":0.05, "y":0.45}
            size_hint: 0.4, 0.15

        TextInput:
            id: text_input
            font_size: (50)
            multiline: False
            pos_hint: {"x": 0.5, "y":0.45}
            size_hint: 0.4, 0.1

        Button:
            pos_hint:{"x":0.68, "y": 0.05}
            size_hint:0.3,0.1
            font_size: (50)
            background_color: .1, .1, .1, .1
            text: "Submit"
            on_release:
                root.submitPatient()