pythongpiozero

Can you bind two functions to button.when_pressed in python gpiozero?


I am trying to bind two functions to a button, so for example I want to toggle a buzzer and LED with a single button. Is there a way to attach two functions to the same button or can a button only do a single thing at once?

For example:

button.when_pressed = led.toggle && buzzer.toggle

Solution

  • You can use 2 solutions. Just merge the two functions into a single function, then call up that single function with the button, or alternatively using a lambda

    SOLUTION N.1

    def ledtoggle_buzzertoggle():
        led.toggle()
        buzzer.toggle()
    
    button.when_pressed = ledtoggle_buzzertoggle
    

    SOLUTION N.2

    You can also use lambda

    button.when_pressed = lambda:[led.toggle(), buzzer.toggle()] #or without square brackets