当我在app类中实例化这样的两个类(MainBoxLayout和Connection)时:
class MartyApp(App, BoxLayout):
def build(self):
self.title = 'Marty Robot App'
self.orientation = 'vertical'
self.add_widget(MainBoxLayout())
self.add_widget(Connection())
return self
如何访问我的kivy文件的Connection
部分中的<MainBoxLayout>:
类/实例?这里:
<MainBoxLayout>:
canvas:
Color:
rgb: [.121, .545, .912]
Rectangle:
pos: self.pos
size: self.size
<Connection>:
available_martys: spinner_discovered_martys.values
rows: 4
cols: 1
padding: 5
我尝试在Connection
类中创建实例化MartyApp
类,将其作为参数传递给MainBoxLayout
类并返回该实例,但随后我的应用程序直接崩溃我不知道为什么。
这是一个例子:
class MartyApp(App, BoxLayout):
conncetion = Conncetion()
def build(self):
return MainBoxLayout(conncetion)
答案 0 :(得分:1)
您可以在构建方法中执行self.connection = Connection()
之类的操作,然后使用App.get_running_app().connection
获取该对象,或者在kv代码中等效app.connection
。
答案 1 :(得分:1)
您必须声明一个ObjectProperty以连接到您的Connection子窗口小部件。有关详细信息,请参阅下面的示例。
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty, NumericProperty
class Connection(GridLayout):
value = NumericProperty(0)
class MainBoxLayout(BoxLayout):
avail_martys = ObjectProperty(None)
def __init__(self, **kwargs):
super(MainBoxLayout, self).__init__(**kwargs)
self.access_connection()
def access_connection(self):
print(self.avail_martys.value)
class MartyApp(App):
def build(self):
self.title = "Marty Robot App"
return MainBoxLayout()
if __name__ == "__main__":
MartyApp().run()
#:kivy 1.10.0
<Connection>:
GridLayout:
rows: 4
cols: 1
padding: 5
<MainBoxLayout>:
avail_martys: conn
canvas:
Color:
rgb: [0.121, .545, 0.912]
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
orientation: "vertical"
Connection:
id: conn