处理其组件需要保持模块化的项目。我在一个需要变量(StatusLabel
)的不同文件中有一个Kivy标签(alarm
),我宁愿将它传递给构造函数,def __init__(self, alarm, **kwargs):
我无法形象在构建画布的其余部分时如何做到这一点。
如何将Jarvus的self.alarm
传递给 gui.py 文件的StatusLabel
?
这是当前非功能状态的变通方法。在gui.py
中,我尝试双重导入(jarvus.py
导入gui
)来访问该属性。这不是我想要的解决方案。
主要档案:jarvus.py
import comms
import alarm
import gui
from kivy.app import App, Builder
class Jarvus(App):
comms_system = comms.Comms()
alarm = alarm.Alarm(comms_system)
def build(self):
# comms thread
self.comms_system.setDaemon(True)
self.comms_system.start()
self.comms_system.log("comms started")
# alarm thread
self.alarm.setDaemon(True)
self.alarm.start()
self.comms_system.log("alarm started")
# this WOULD work if I only wanted the single widget
# return gui.StatusLabel(self.alarm)
# How can I get self.alarm into this Builder?
return Builder.load_string(gui.KV)
Jarvus().run()
GUI元素 gui.py
KV = '''
<ScreenManagement>:
HomeScreen:
BoxLayout:
<HomeScreen>:
BoxLayout:
<StatusLabel>:
'''
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.config import Config
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
from kivy.lang import Builder
from kivy.clock import Clock
class ScreenManagement(ScreenManager):
def __init__(self, **kwargs):
self.transition = SlideTransition()
# HERE'S THE PROBLEM
class StatusLabel(Label):
def __init__(self, alarm, **kwargs):
# kivy stuff
super(StatusLabel, self).__init__(**kwargs)
# make the button update
self.font_size = 24
Clock.schedule_interval(self.update, .1)
# self.alarm = alarm
self.id = 'status'
def update(self, *args):
try:
from jarvus import Jarvus
self.text = Jarvus.alarm.now()
except Exception:
return
class HomeScreen(Screen):
def __init__(self, **kwargs):
self.name = 'home'
self.orientation = 'vertical'
self.add_widget(StatusLabel())
答案 0 :(得分:1)
您无法将其传递给StatusLabel
,因为您在调用Builder.load_string
时甚至没有创建StatusLabel。
您正在定义一个模板,从现在开始将用于所有StatusLabel
。
如果你想传递一个可由kivy解析器解析的默认值,那么你可以调整gui.KV
以包含一个可以在调用Builder.load_string
之前替换的模式,但这不是这里的情况。