【发布时间】:2016-06-20 10:57:15
【问题描述】:
我在理解自定义属性的使用以及将方法绑定到事件的方式方面遇到问题。 这是我的代码:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.properties import StringProperty
kivy_lang = '''
<MainWidget>:
on_my_property: my_label.text = 'from button bind method via StringProperty' + my_property
Label:
id: my_label
text: root.my_property
Button:
id: my_button
text: 'intro button'
'''
class MainWidget(BoxLayout):
# bind some properties
my_property = StringProperty('0')
def __init__(self, **kwargs):
super(MainWidget, self).__init__(**kwargs)
# if needed to do sth on widget construction
self.ids.my_button.bind(on_press=self.my_method)
def my_method(self,*args,**kwargs):
self.my_property = str(int(self.my_property)+1)
self.ids.my_button.text = 'new'
class MyApp(App):
def build(self):
Builder.load_string(kivy_lang)
return MainWidget()
if __name__ == '__main__':
MyApp().run()
当我运行它时,它呈现正常,但是当我单击一个按钮时,结果我得到 NameError: name 'my_property' 未定义
我尝试使用 kv lang 中的 Button 绑定方法(并在 python 端删除整个 'init()'):
on_press: root.my_method
然后当我按下按钮时,应用程序不会崩溃,但什么也没发生
有人可以解释一下如何调整此代码以使其正常工作吗? 我知道代码有点“混合技术”,但我这样做是为了了解不同的方法,所以如果你不把它全部转过来,我将不胜感激:)
【问题讨论】:
标签: python properties bind kivy