0

目标:

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()
4

1 回答 1

0

您可以通过实例访问小部件文本和 ID:

  def mycallback(self,instance):
            m=instance.id 
            x=instnace.text

它决定了行,你可以处理它。添加时必须将 id 添加到小部件。我没有用 on_touch_down 尝试过,但我用 on_press 试过了,它有效。

您可以在 add_widget 时调用 my_callback 函数,如下所示:

self.ids.scroll.add_widget(OneLineListItem(text='as you want' ,id=str(i),halign="right",on_press=self.mycallback))
于 2020-08-21T16:25:36.183 回答