2016-07-27 36 views
0

是否可以在多個對象中綁定on_dropfile?或者它總是隻有一個綁定?kivy on_dropfile多個綁定

我decalred類

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" 

但只適用於第一個字段(它只能看到那些上被丟棄的文件「請刪除file1「字段,在其他情況下,它會收到放置,但無法確認它位於第二個字段的邊界,就好像它只綁定第一個對象的on_dropfile函數一樣)。

是否有任何優雅的方式來實現它的多個對象?

回答

0

現在它對我更有意義。在這種情況下,爲什麼不只是在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() 

似乎對我很好。 Windowon_dropfile直接相關,在App類中處理,另一個在其相應的函數中。

+0

感謝您的回覆。 我知道班級是如何工作的。 助手只是一個空的'類助手'來保存鼠標的位置,我已經將'Window.bind(mouse_pos = lambda w,p:setattr(helper,'mpos',p))'行'移到了主類因此它不會被執行多次。 它不像'on_release'那樣工作,因爲'on_dropfile'是一個窗口事件,而不是小部件事件,不幸的是我不能將它與kv綁定,因爲它會拋出異常。 我已經轉移到PyQt,因爲它似乎更適合桌面應用程序(Kivy可能會說這是所有的,但是爲移動而精簡)。 但問題仍然有效 – sanki

+0

@sanki我編輯它,所以它的工作 – KeyWeeUsr

+0

謝謝,對於新的編輯,這似乎工作得更好:-) – sanki