我正在编写一个程序,该程序的右边有一个按钮面板,成功地将一个方法绑定到每个方法,这取决于用户的输入/操作。我的问题是,由于方法绑定是动态的,所以我无法解释unbind()
方法。
考虑;
i = 1
while i <= 8:
string = "action" + str(i)
#Buttons named 'action1, action1, ..., action8'
ref = self.ids[string]
ref.text = ""
observers = ref.get_property_observers('on_release')
print observers
ref.unbind()
ref.bind(on_release=partial(self.BlankMethod, arg1))
i += 1
线条;
observers = ref.get_property_observers('on_release')
print observers
每次调用该方法时,我都会显示越来越多的弱方法绑定,但是unbind函数不会解除该方法的绑定。
虽然我的代码示例没有显示它,但是绑定方法经常发生变化,而且self.BlankMethod
是用来覆盖原始绑定的。情况并非如此,Button
的边界方法也增加了。
[<kivy.weakmethod.WeakMethod object at 0x7f8cc826a810>]
[<kivy.weakmethod.WeakMethod object at 0x7f8cc826a850>, <kivy.weakmethod.WeakMethod object at 0x7f8cc826acd0>]
我试过了;
observers = ref.get_property_observers('on_release')
if observers != []:
for observer in observers:
ref.unbind(observer)
ref.bind(on_release=partial(self.Blank))
但我得到了回报的错误;
TypeError: unbind() takes exactly 0 positional arguments (1 given)
我看过使用funbind()
函数,但随后给出了;
AttributeError: 'Button' object has no attribute 'funbind'
尝试在fbind()
之前使用funbind()
也会产生同样的错误,但是对于没有fbind()
属性的按钮。
如何列出对象的所有绑定方法,并随后解除绑定?
发布于 2016-02-11 02:38:05
下面是一个演示设置、保存和稍后清除回调的玩具示例。当按下a_button
或b_button
时,会触发set_callbacks
,它将回调绑定到所有MyButton
。MyButton
有一个list属性_cb
存储用户定义的回调。c_button
将触发clear_callbacks
,它将遍历MyButton
的每个_cb
列表,并解除对每个存储回调的绑定。
from kivy.app import App
from kivy.lang import Builder
from functools import partial
kv_str = """
<MyButton@Button>:
_cb: []
my_id: 1
text: "hello {}".format(self.my_id)
BoxLayout:
orientation: 'vertical'
BoxLayout:
Button:
id: a_button
text: "a button"
Button:
id: b_button
text: "b button"
Button:
id: c_button
text: "clear callbacks"
GridLayout:
cols: 4
id: grid
MyButton:
my_id: 1
MyButton:
my_id: 2
MyButton:
my_id: 3
MyButton:
my_id: 4
"""
def cb(sender, arg='nothing'):
print "we got: {} pressed with {}".format(sender.text, arg)
class MyApp(App):
def build(self):
root = Builder.load_string(kv_str)
def set_callbacks(sender):
for b in root.ids.grid.children:
new_cb = partial(cb, arg=sender.text)
b._cb.append(new_cb)
b.fbind('on_press', new_cb)
def clear_callbacks(sender):
for b in root.ids.grid.children:
for cb in b._cb:
b.funbind('on_press', cb)
b._cb = []
root.ids.a_button.bind(on_press=set_callbacks)
root.ids.b_button.bind(on_press=set_callbacks)
root.ids.c_button.bind(on_press=clear_callbacks)
return root
if __name__ == '__main__':
a = MyApp()
a.run()
https://stackoverflow.com/questions/35328271
复制相似问题