目标:
my_callback()
-仅在按下小部件时调用函数OneLineListItem
,否则什么也不做。
解释这些事情:
-请解释我如何在按下my_callback()
任何一个时调用该函数OneLineListItem
,使用 on_touch_down() 函数
- 还要解释为什么我们要super(Touch, self).on_touch_down(touch)
在else
块中添加
当前代码的问题:
- 不要给出任何错误,但代码不能按我的意愿工作。
-on_touch_down()
该方法不起作用(想了解它是如何工作的,我刚刚从 kivy 的文档中复制了它)。
from kivymd.app import MDApp
from kivy.lang import Builder
from kivymd.uix.list import OneLineListItem
from kivy.uix.widget import Widget
helper_string = """
Screen:
Touch:
ScrollView:
MDList:
id: containers
"""
class MyApp(MDApp):
def build(self):
screen = Builder.load_string(helper_string)
return screen
def on_start(self):
# createing the OneLineListItem
item_1 = OneLineListItem(text='subject_1', id='item1')
item_2 = OneLineListItem(text='subject_2', id='item2')
item_3 = OneLineListItem(text='subject_3', id='item3')
# adding the above OneLineListItem into MDList
self.root.ids.containers.add_widget(item_1)
self.root.ids.containers.add_widget(item_2)
self.root.ids.containers.add_widget(item_3)
class Touch(Widget):
def on_touch_down(self, touch):
app = MDApp.get_running_app()
# gets all the OneLineListItem in subject_wid_list
subject_wid_list = app.root.ids.containers.children
# plz explain this part briefly. have lots of confusion about .collide_point()
# also explain why we are adding super(...).on_touch_down()
# iterating in the list and checking for collision of widget with touched coordinates.
for child in subject_wid_list:
if child.collide_point(*touch.pos):
print('touched one of the OneLineListItem widget')
self.my_callback()
else:
print('touched something else other than OneLineListItem widget')
return super(Touch, self).on_touch_down(touch)
def my_callback(self):
pass
MyApp().run()