問題描述
后續問題:Kivy 外部規則繼承
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:
文件main.py",第 18 行,在 AddFancy 中temp = Factory.FancyButton(text='f', imp = self.ids.imp)文件properties.pyx",第 756 行,在 kivy.properties.ObservableDict.__getattr __ (kivy/properties.c:11093)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 __'
跟進問題
Kivy 外部規則繼承 2
推薦答案
Widget.ids
僅包含其子項的 id (http://kivy.org/docs/api-kivy.uix.widget.html#kivy.uix.widget.Widget.ids. 不需要小部件本身的 ID,因為您可以直接傳遞它 - 在您的情況下使用 self
,因為您從內部傳遞對小部件的引用一種方法:
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 規則的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!