1

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

2 Answers2

3

Bind to a function that calls both functions:

def toggle_led_and_buzzer():
    led.toggle()
    buzzer.toggle()

button.when_pressed = toggle_led_and_buzzer
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

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
Erling Olsen
  • 1
  • 4
  • 15