0
我在理解自定义特性的用法以及将事件绑定方法的方法时遇到了问题。 这里是我的代码:了解Kivy特性和绑定方法
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()
当我运行它,它呈现OK,但是当我点击一个按钮,结果我得到 NameError:名字“my_property”没有定义
我想结合的方法对于巴顿在KV与郎(和删除在Python端整体“初始化()”):
on_press: root.my_method
,然后当我按下按钮的应用程序不会崩溃,但什么也没有发生
有人可以解释我如何调整此代码的工作? 我明白代码有点“混合技术”,但我这样做是为了了解不同的方法,所以我将不胜感激,如果你不把它全部围绕:)
不错,感谢您的快速回复 - 看起来我毕竟不是那么远:) 所以我需要记住: 1)&2) - 在kv lang中':'之后写什么不是真的是一个绑定在任何点, **它总是一个python代码执行'原样'**当属性更新(因此'自我。'是需要引用属性/属性当前实例的小部件) – simplynail