【Kivy】特定のウィジェットにファイルをドラッグ&ドロップする

  • main.py
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.label import Label

class MainApp(App):
    def build(self):
        Window.bind(on_dropfile=self.on_dropped_file)
        return
    def get_collide_widgets(self, collide_widgets, widget, pos):
        # children
        for child_widget in widget.children:
            self.get_collide_widgets(collide_widgets, child_widget, pos)
        # widget
        if widget.collide_point(pos[0], pos[1]):
            collide_widgets.append(widget)
    def on_dropped_file(self, window, file_path):
        widgets = []
        self.get_collide_widgets(widgets, self.root, window.mouse_pos)
        
        text: str = ''
        for widget in widgets:
            if isinstance(widget, Label):
                text += widget.text
                text += ', '
        self.root.text = '{}'.format(text)

if __name__ == '__main__':
    MainApp().run()
  • main.kv
#:kivy 1.0
MainWidget:
<MainWidget@FloatLayout>
    text: ''
    FloatLayout:
        name: 'FloatLayout 1'
        Label:
            text: 'Label 1'
            size_hint: 0.75, 0.75
            pos_hint: {'x':0.0, 'y':0.0}
            canvas:
                Color:
                    rgba: 1.0, 0.0, 0.0, 0.25
                Rectangle:
                    pos: self.pos
                    size: self.size
        Label:
            text: 'Label 2'
            size_hint: 0.75, 0.75
            pos_hint: {'x':0.25, 'y':0.0}
            canvas:
                Color:
                    rgba: 0.0, 1.0, 0.0, 0.25
                Rectangle:
                    pos: self.pos
                    size: self.size
    FloatLayout:
        name: 'FloatLayout 2'
        Label:
            text: 'Label 3'
            size_hint: 0.75, 0.75
            pos_hint: {'x':0.0, 'y':0.25}
            canvas:
                Color:
                    rgba: 0.0, 0.0, 1.0, 0.25
                Rectangle:
                    pos: self.pos
                    size: self.size
        Label:
            text: 'Label 4'
            size_hint: 0.75, 0.75
            pos_hint: {'x':0.25, 'y':0.25}
            canvas:
                Color:
                    rgba: 1.0, 1.0, 1.0, 0.25
                Rectangle:
                    pos: self.pos
                    size: self.size
    Label:
        text: root.text
        text_size: self.size
        size_hint: 1.0, None
        size: 1.0, 50
        pos_hint: {'x':0.0, 'y':0.0}
  • 結果

youtu.be