将kv语言与Python代码链接起来

时间:2014-04-03 06:45:47

标签: python kivy

在使用id如下链接kv和python代码的基本示例中了解到:

请考虑my.kv中的以下代码:

<MyFirstWidget>:
    # both these variables can be the same name and this doesn't lead to
# an issue with uniqueness as the id is only accessible in kv.
txt_inpt: txt_inpt
Button:
    id: f_but
TextInput:
    id: txt_inpt
    text: f_but.state
    on_text: root.check_status(f_but)

在myapp.py中:

class MyFirstWidget(BoxLayout):

    txt_inpt = ObjectProperty(None)

    def check_status(self, btn):
        print('button state is: {state}'.format(state=btn.state))
        print('text input text is: {txt}'.format(txt=self.txt_inpt))

并且此代码有效,即我们可以使用txt_inpt访问Label。我试图在我的代码中为按钮做同样的事情,但我收到一个错误:

play_Button.text = 'hello'

AttributeError:&#39; kivy.properties.ObjectProperty&#39;对象没有属性&#39; text&#39;

见下面的代码:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
from kivy.graphics import Color


gui = '''
<MenuScreen>:
    play_Button: playButton
    GridLayout:

        size_hint: .2, .2
        pos_hint: {'center_x': .5, 'center_y': .5}
        rows: 1
        Button:
            id: playButton
            text: 'Play !'

'''

class MenuScreen(Screen):
    play_Button = ObjectProperty(None)
    def __init__(self, **kwargs):
        super(MenuScreen, self).__init__(**kwargs)
        #If i use below one it works
        #self.ids.playButton.text = 'hello'

    Builder.load_string(gui)
    play_Button.text = 'hello'
    pass

class MyJB(App):
    def build(self):
        sm = ScreenManager()
        sm.add_widget(MenuScreen(name='menu'))
        return sm

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

如果我使用ids.play_Button它按预期工作但似乎我做错了另一种方式。有人可以建议吗?

1 个答案:

答案 0 :(得分:2)

class MenuScreen(Screen):
    play_Button = ObjectProperty(None)
    def __init__(self, **kwargs):
        super(MenuScreen, self).__init__(**kwargs)
        #If i use below one it works
        #self.ids.playButton.text = 'hello'

    Builder.load_string(gui)
    play_Button.text = 'hello'
    pass

您在这里缺少一些缩进,play_Button.text行应该在__init__方法中(并且pass什么都不做,所以您可以删除它)。这是SO或您实际代码中的拼写错误吗?

如果它在你的实际代码中,它会导致给定的错误,因为它是在声明类时运行的,而不是在实例化类的实例时运行。这意味着它不会看到objectproperty所持有的对象,而只是ObjectProperty本身......它(根据错误)没有属性'text'。

在应用的build方法中加载kv字符串,甚至在任何类之外加载kv字符串也更为正常。

相关问题