python-3.xfunctionkivykivy-languagealternate

How can I switch between 2 on_release on kivy?


I want to know how I do to give the 1 kivy button two features, for example a pause and unpause button, where when I click pause, it changes the value from on_release to another function, and when you click again, it goes back to the first, and so on.

I tried this:

======= Main.py =======

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class Main(BoxLayout):
    pass

class test(App):
    def build(self):
        return Main()

    def Pause(self):
        Main().ids.pause_unpause.on_release = self.Unpause
        print('Paused')

    def Unpause(self):
        Main().ids.pause_unpause.on_release = self.Pause
        print('Unpaused')


test().run()

======= test.kv =======

<Main>:
    Button:
        id: pause_unpause
        on_release: app.Pause()

But he does not switch functions, can someone help me?


Solution

  • Two problems with your code:

    1. Calls to Main() in your methods create a new instance of Main that is not the Main that appears in your GUI. So calling any methods on those new instances will have no effect on your GUI.
    2. Changing the on_release binding of a Button during the processing of the on_release event will probably cause unexpected results.

    I suggest just using a single on_release method that keeps track of the paused/unpaused state:

    class test(App):
        is_paused = BooleanProperty(False)
    
        def build(self):
            return Main()
    
        def Pause_Unpause(self):
            self.is_paused = not self.is_paused
            if self.is_paused:
                print('Paused')
            else:
                print('Unpaused')
    

    And the corresponding kv:

    <Main>:
        Button:
            id: pause_unpause
            on_release: app.Pause_Unpause()