python - kivy on_dropfile 多重绑定(bind)

标签 python drag-and-drop kivy kivy-language

是否可以在多个对象中绑定(bind)on_dropfile?或者它总是只有一个绑定(bind)?

我已经贴上类(class)标签

class dropFile(Label):
    def __init__(self, **kwargs):
        super(dropFile, self).__init__(**kwargs)
        Window.bind(mouse_pos=lambda w, p: setattr(helper, 'mpos', p))
        Window.bind(on_dropfile=self.on_dropfile)

    def on_dropfile(self, *args):
        print ("ding")
        if (self.center_x - self.width/2 < helper.mpos[0] < self.center_x + self.width/2 and
                self.center_x - self.height/2 < helper.mpos[1] < self.center_y + self.height/2):
            print('dong')
            self.text = str(args[1])

在 kv 中我只是将其用作

dropFile:
    text: "Please drop file1"
dropFile:
    text: "Please drop file2"

但仅适用于第一个字段(它只看到在“请删除文件1”字段上删除的文件,在其他情况下,它收到删除,但无法确认它在第二个字段的范围内,如如果它只绑定(bind)第一个对象的 on_dropfile 函数)。

有没有什么优雅的方式来实现多个对象?

最佳答案

现在对我来说更有意义了。在这种情况下,为什么不创建一个列表并在 Window.on_dropfile 上执行您喜欢的任何函数?

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
Builder.load_string('''
<DropFile>:
<Box>:
    DropFile:
        text: 'left'
    DropFile:
        text: 'right'
''')

class Box(BoxLayout):
    pass

class Test(App):
    def build(self):
        self.drops = []
        Window.bind(on_dropfile=self.handledrops)
        return Box()
    def handledrops(self, *args):
        for i in self.drops:
            i(*args)

class Helper:
    pass

class DropFile(Label):
    def __init__(self, **kwargs):
        super(DropFile, self).__init__(**kwargs)
        Window.bind(mouse_pos=lambda w, p: setattr(Helper, 'mpos', p))
        app = App.get_running_app()
        app.drops.append(self.on_dropfile)

    def on_dropfile(self, *args):
        print ("ding")
        if (self.center_x - self.width/2 < Helper.mpos[0] < self.center_x + self.width/2 and
                self.center_x - self.height/2 < Helper.mpos[1] < self.center_y + self.height/2):
            print('dong')
            self.text = str(args[1])

Test().run()

对我来说似乎效果很好。 Window 的异常与 App 类中的 on_dropfile 句柄直接相关,其他异常在其相应的函数中。

关于python - kivy on_dropfile 多重绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38617194/

相关文章:

python - Kivy kv 文件的行为与 Builder.load_string 不同

spinner - 动态更改 Kivy Spinner 值

python - 在其他类方法中定义新的类实例 - Python

python - 如何简化这种Python代码?

Python方式来检查互联网广播流是否可用/直播

javascript - 将 "dragstart"事件附加到 "mouseup"以获​​得可拖动体验

javascript - HTML5 拖放与 jQuery UI 拖放

HTML5 拖放数据传输和 Chrome

python - 如何让 Kivy 1.9.1 或 1.9.2 在 OSX 10.12.2 上使用 SDL2 而不是 pygame?

创建递减序列列表的 Pythonic 方法