繁体   English   中英

想要在使用 on_touch_down 方法单击它时访问小部件(此处为 OneLineListItem)的文本和 id

[英]want to access the widget's (here OneLineListItem) text and id when it is clicked using on_touch_down method

目标:

- 仅在按下OneLineListItem小部件时调用my_callback() function,否则什么也不做。

解释这些事情:

- 请解释我如何在按下 OneLineListItem 中的任何一个时调用OneLineListItem my_callback() ,使用 on_touch_down() function

- 还解释为什么我们在else块中添加super(Touch, self).on_touch_down(touch)

当前代码的问题:

- 不要给出任何错误,但代码不能按我的意愿工作。

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

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

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

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

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

self.ids.scroll.add_widget(OneLineListItem(text='as you want' ,id=str(i),halign="right",on_press=self.mycallback))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM