【发布时间】:2021-10-01 09:00:36
【问题描述】:
代码说明: 我有两个用于 ScreenList 对象的 id(proof_list 和 menu_list)。当我点击一个列表项(instance_item)时,我想要他们关联的父母的 id。 check_id 函数应该通过调用 get_id(instance_item.parent) 来打印其父级的 id,即 proof_list 或 menu_list。
问题: get_id 不检索 self.root.ids 完整字典。我通过打印结果进行了检查,结果是一个空字典。出于好奇,我尝试在我的 on_start 方法中打印 self.root.ids,它提供了一个完整的 id 字典。我需要在get_id中访问self.root.ids,所以它可以检查一个实例是否在那个id字典中,如果为真则返回它的id。
问题: 我相信这是一个初始化问题,但我不知道从哪里开始解决这个问题。所以我的问题是:
- 为什么会在 on_start 方法中给出完整的字典?
- 我的 get_id 方法如何像 on_start 方法一样检索完整的 id 字典?
我知道我的问题与初始化有关。但是,我仍在学习中,不知道该怎么做,所以我很感激你的帮助。
这是一个非常简化的代码示例。
from kivymd.app import MDApp
from kivymd.theming import ThemableBehavior
from kivy.lang import Builder
from kivymd.uix.list import MDList, OneLineListItem, TwoLineListItem, ThreeLineListItem, ThreeLineIconListItem, \
OneLineIconListItem
from kivy.core.window import Window
from proof_nav import proof_helper
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty, StringProperty
class ScreenList(ThemableBehavior, MDList):
screen_manager = ObjectProperty()
def check_id(self, instance_item):
e1 = ProofApp()
parent_id = e1.get_id(instance_item.parent)
print(parent_id)
class ProofApp(MDApp):
def build(self):
screen = Builder.load_string(proof_helper)
return screen
def on_start(self):
print(self.root.ids)
def get_id(self, instance_item):
for id, widget in self.root.ids.items():
if instance_item == widget:
print(self.root.ids)
return str(id)
print(self.root.ids)
return ""
ProofApp().run()
这是我加载的字符串文件:
proof_helper = """
Screen:
MDNavigationLayout:
ScreenManager:
id: screen_manager
Screen:
name: 'menu'
BoxLayout:
orientation: 'vertical'
MDToolbar:
title: "Menu Screen"
elevation: 8
ScrollView:
ScreenList:
id: menu_list
screen_manager:screen_manager
OneLineListItem:
text: "Some Item"
on_release: self.parent.check_id(self)
Screen:
name: 'screen2'
BoxLayout:
orientation: 'vertical'
MDToolbar:
title: "Proofs"
elevation: 8
ScrollView:
ScreenList:
id: proof_list
screen_manager:screen_manager
OneLineListItem:
text: "Another Item"
on_release: self.parent.check_id(self)
"""
【问题讨论】:
-
告诉我们你是怎么打电话给
get_id()的。 -
感谢您的反馈!我刚刚在我的帖子中添加了更多信息。如果还不清楚,请告诉我。