AttributeError:' NoneType'对象没有属性' text'在python中

时间:2018-03-22 06:05:19

标签: python kivy kivy-language

我正在使用python-2.7kivy。当我运行test.py时,它会显示错误AttributeError: 'NoneType' object has no attribute 'text' in python? 有人告诉我什么是错误?

test.py

import kivy

kivy.require('1.9.0')  # replace with your current kivy version !
from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.properties import ObjectProperty


Window.size = (500, 230)


class GroupScreen(Screen):
    groupName = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(GroupScreen, self).__init__(**kwargs)
        self.groupName.text = "Test"


class Group(App):

    def build(self):
        self.root = Builder.load_file('test.kv')
        return self.root



if __name__ == '__main__':
    Group().run()

test.kv

GroupScreen:
    groupName:groupName

    GridLayout:
        cols: 2
        padding : 30,30
        spacing: 10, 10
        row_default_height: '40dp'

        Label:
            text: 'Test'

        SingleLineTextInput:
            id: groupName

        GreenButton:
            text: 'Ok'

        GreenButton:
            text: 'Cancel'

        Label:

        Label:



<SingleLineTextInput@TextInput>:
    multiline: False


<GreenButton@Button>:
    background_color: 1, 1, 1, 1
    size_hint_y: None
    height: self.parent.height * 0.150

1 个答案:

答案 0 :(得分:1)

如果要在.kv中创建对象:

GroupScreen:
    groupName:groupName
    ...

然后没有必要在.py中声明它。

另一方面,向窗口小部件添加子项不是即时的,因此在这些情况下始终建议使用Clock

import kivy

kivy.require('1.9.0')  # replace with your current kivy version !
from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.clock import Clock


Window.size = (500, 230)


class GroupScreen(Screen):
    def __init__(self, **kwargs):
        super(GroupScreen, self).__init__(**kwargs)
        Clock.schedule_once(lambda dt: setattr(self.groupName, 'text', "Test"))

class Group(App):
    def build(self):
        self.root = Builder.load_file('test.kv')
        return self.root


if __name__ == '__main__':
    Group().run()