简体   繁体   中英

Kivy: bind two methods to be called one after the other

I have a class C with two methods, a and b, and i want one of them (b) to be always called after the other (a)

class C(Widget) :
 def __init__(self) :
  super(C, self).__init__() 
  self.bind(a=self.b)  # something like this 
 def a(self) : pass
 def b(self) : pass

How?

How about calling b from a.

def a(self) :
    #some code
    self.b()

I don't quite remember why doesn't it work through binding, but I think it has something to do with using different objects eg binding to an old method that isn't executed or something in that sense.

This is where super() comes to the rescue. You see, super() isn't only for calling __init__() of the class you inherit from, it has other purposes too.

I just replaced __init__() with <overridden method>() :

from kivy.base import runTouchApp
from kivy.uix.button import Button

class MyBase(Button):
    def overridden(self, *args):
        self.stable()

    def stable(self, *args):
        print('stable')

class MyButton(MyBase):
    def __init__(self, **kwargs):
        super(MyButton, self).__init__(**kwargs)
        self.bind(on_release=self.overridden)

    def overridden(self, *args):
        # run before overriden stuff
        super(MyButton, self).overridden()

        print('new overridden')

        # run after overridden stuff
        super(MyButton, self).overridden()
runTouchApp(MyButton())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM