使用add_widget()的Kivy规则继承 [英] Kivy rule inherence with add_widget()
问题描述
跟进问题:摆脱规则外在的固有性
main.py
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.stacklayout import StackLayout
from kivy.properties import ObjectProperty
from kivy.factory import Factory
class FancyButton(Button):
imp = ObjectProperty(None)
class Important(StackLayout):
def NoInspiration(self, smile):
print("Received: {}".format(smile))
def AddFancy(self):
temp = Factory.FancyButton(text='f', imp = self.ids.imp)
self.ids.boxy.add_widget(temp)
class TestApp(App):
def build(self):
pass
if __name__ == '__main__':
TestApp().run()
test.kv
#:kivy 1.9.0
#:import App kivy.app
<FancyButton>:
on_release: self.imp.NoInspiration(':)')
<Important>:
id: imp
BoxLayout:
id: boxy
orientation: 'vertical'
FancyButton:
text: "smiley"
imp: root
Button:
text: "add fancy"
on_release: imp.AddFancy()
BoxLayout:
Important
在test.kv中,可以对FancyButton中的函数NoInspiration()进行调用,因为.kv中定义的FancyButton具有imp:root,因此它知道应该在<中查找该函数.重要>:.
In test.kv the function call in FancyButton to the function NoInspiration() works, because the FancyButton defined in the .kv has imp: root, so it knows it should look for the function in < Important >:.
但是,当您通过Python中的add_widget创建FancyButton时,imp:root是如何工作的?
However how does imp: root work when you create FancyButton through add_widget in Python?
现在,当我按下添加花式"按钮时,我得到了错误消息:
Now when I press the button "add fancy" I get the error:
AddFancy中的文件"main.py",第18行 temp = Factory.FancyButton(text ='f',imp = self.ids.imp) 在kivy.properties.ObservableDict .__ getattr __(kivy/properties.c:11093)中,文件"properties.pyx",行756 AttributeError:'super'对象没有属性'__getattr __'
File "main.py", line 18, in AddFancy temp = Factory.FancyButton(text='f', imp = self.ids.imp) File "properties.pyx", line 756, in kivy.properties.ObservableDict.__getattr __ (kivy/properties.c:11093) AttributeError: 'super' object has no attribute '__getattr __'
关注问题
推荐答案
Widget.ids
only contain ids of its children (http://kivy.org/docs/api-kivy.uix.widget.html#kivy.uix.widget.Widget.ids. Id of the widget itself it's not needed because you can just pass it directly - in your case using self
, since you're passing a reference to a widget from inside of a method:
class Important(StackLayout):
def NoInspiration(self, smile):
print("Received: {}".format(smile))
def AddFancy(self):
print(self.ids) # only returns {'boxy': <weakproxy at 0000000002D119A8 to BoxLayout at 0000000002D026A8>}
self.ids.boxy.add_widget(FancyButton(text='f', imp = self)) # no need to use a factory
这篇关于使用add_widget()的Kivy规则继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!