类 使用 kivy 布局
Classes with kivy layout
我希望使用 kivy 语言定义一个小部件,但我想向 class 添加函数。下面是我天真的尝试,当我点击带有消息 "AttributeError: 'MyButton' object has no attribute 'second_pressed'"
的按钮时失败了
如何制作具有函数和 kivy 语言定义外观的 class?
import sys
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
root = Builder.load_string('''
BoxLayout:
Label:
text: 'hello'
MyButton:
<MyButton@Button>:
text: 'Second button'
on_press: self.second_pressed()
''')
class MyButton():
def second_pressed():
print "second pressed"
sys.stdout.flush()
class Tryit(App):
def build(self):
return root
if __name__ == '__main__':
Tryit().run()
<MyButton@Button>:
这定义了一个动态的 new class,命名为 MyButton
,它与你的 python 中的 MyButton
无关] 您为其添加该方法的代码。
要使其正常工作,只需编写 <MyButton>:
,表示现有 class 的规则。您可能还需要将 Builder.load_string
延迟到声明此 class 之后 - 通常最好在 App 的 build
方法中执行此操作,因为此时保证会初始化所有重要内容.
我希望使用 kivy 语言定义一个小部件,但我想向 class 添加函数。下面是我天真的尝试,当我点击带有消息 "AttributeError: 'MyButton' object has no attribute 'second_pressed'"
的按钮时失败了
如何制作具有函数和 kivy 语言定义外观的 class?
import sys
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
root = Builder.load_string('''
BoxLayout:
Label:
text: 'hello'
MyButton:
<MyButton@Button>:
text: 'Second button'
on_press: self.second_pressed()
''')
class MyButton():
def second_pressed():
print "second pressed"
sys.stdout.flush()
class Tryit(App):
def build(self):
return root
if __name__ == '__main__':
Tryit().run()
<MyButton@Button>:
这定义了一个动态的 new class,命名为 MyButton
,它与你的 python 中的 MyButton
无关] 您为其添加该方法的代码。
要使其正常工作,只需编写 <MyButton>:
,表示现有 class 的规则。您可能还需要将 Builder.load_string
延迟到声明此 class 之后 - 通常最好在 App 的 build
方法中执行此操作,因为此时保证会初始化所有重要内容.