хотите получить доступ к тексту и идентификатору виджета (здесь OneLineListItem) при нажатии с помощью метода on_touch_down

#python #python-3.x #kivy #kivy-language #kivymd

#python #python-3.x #kivy #kivy-language #kivymd

Вопрос:

ЦЕЛЬ:

-вызывайте 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()
  

Ответ №1:

Вы получаете доступ к тексту и идентификатору виджета через экземпляр:

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

он определяет строку, и вы можете с ней справиться. Вы должны добавить идентификатор к виджету при его добавлении. Я не пробовал это с помощью on_touch_down, но у меня есть с помощью on_press, и это сработало.

Вы можете вызвать функцию my_callback при добавлении_widget следующим образом:

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