我正在尝试更改现有的Kivy App,以合并外观漂亮的KivyMD小部件。我删除了Spinner
的{{1}}和MDRaisedButton
的{{1}} on_release
,并删除了已通过蓝牙与设备配对的设备名称列表(具体取决于在平台上)。对于此测试示例,我仅使用caller
文档示例中所示的菜单项列表。
由于某种原因,在初始化MDDropdownMenu
属性时,我收到了MDDropdownMenu
KeyError: 'dev_button'
的{{1}}。 MDRaisedButton
方法在我的根类中,该类位于名为id
和MDDropdownMenu
的文件__init__
和indexui.py
的单独文件中。但是已导入indexui.kv
文件中并包含在main.py
文件中。该应用程序确实在更改main.kv
之前运行。
indexui.py
main.py
indexui.kv
main.kv
main.py
Spinner
main.kv
class RootLay(FloatLayout):
this = ObjectProperty(None) # App object
bserial = ObjectProperty(None) # Bluetooth variables starts
recv_stream = ObjectProperty(None)
send_stream = ObjectProperty(None)
menu = ObjectProperty(None)
rfsocket = ObjectProperty(None)
device = ObjectProperty(None)
pattern = ObjectProperty(None)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.device = None
self.pattern = re.compile(r'[GNSTUkg,\s]')
self.dev_list = []
menu_items = [{"icon": "git", "text": f"Item {i}"} for i in range(5)]
print(dir(self.ids))
self.menu = MDDropdownMenu(
caller=self.ids.dev_button, items=menu_items, width_mult=4
)
self.menu.bind(on_release=self.menu_callback)
有人可以帮我理解为什么会有<RootLay>:
MDToolbar:
pos_hint: {'top': 1, 'right': 1}
title: "Bluetooth Weigh"
MDRaisedButton:
id: dev_button
text: "SEE DEVICES"
pos_hint: {'top': 0.76, 'right': 0.9}
on_release: app.root.menu.open()
吗? from kivymd.app import MDApp
from views.indexui import RootLay
from kivy.properties import ObjectProperty
class MainApp(MDApp):
def build(self):
self.theme_cls.primary_palette = "Yellow" # "Purple", "Red"
self.theme_cls.primary_hue = "600"
# self.icon = 'bluetooth-connected_326502.png'
root = ObjectProperty(RootLay())
return root
def on_pause(self):
return True
MainApp().run()
作为方法在#:include views/indexui.kv
RootLay:
类范围内。因此,我应该能够访问其所有属性。
答案 0 :(得分:1)
我认为问题在于您正在尝试访问ids
类的RootLay
,然后才能使用它们。我建议像这样使用Clock.schedule_once()
来延迟访问:
class RootLay(FloatLayout):
this = ObjectProperty(None) # App object
bserial = ObjectProperty(None) # Bluetooth variables starts
recv_stream = ObjectProperty(None)
send_stream = ObjectProperty(None)
menu = ObjectProperty(None)
rfsocket = ObjectProperty(None)
device = ObjectProperty(None)
pattern = ObjectProperty(None)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.device = None
self.pattern = re.compile(r'[GNSTUkg,\s]')
self.dev_list = []
Clock.schedule_once(self.setup_menu) # delay until ids are available
def setup_menu(self, dt):
menu_items = [{"icon": "git", "text": f"Item {i}"} for i in range(5)]
self.menu = MDDropdownMenu(
caller=self.ids.dev_button,
items=menu_items,
width_mult=4
)
self.menu.bind(on_release=self.menu_callback)