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

2024-04-25 13:12:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

你知道吗主.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()

Tags: textposselfsizedef情况classsm
1条回答
网友
1楼 · 发布于 2024-04-25 13:12:34

说明:

Widget类具有^{}属性,该属性用于存储Widget子类,因此从Widget继承的任何类(如Screen和PredictEstimate)都将具有该属性,但您将使用None覆盖它,从而生成您指示的错误。你知道吗

解决方案:

不要对该属性使用子级,而是使用另一个名称:

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

登录.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()

相关问题 更多 >