简体   繁体   中英

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

Bind to a function that calls both functions:

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

button.when_pressed = toggle_led_and_buzzer

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

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