[Python] GPIO button.when_pressed cannot be used twice

Hi
I am working on a camera using python on a raspberry, and for the buttons setup I am using gpiozero library.
Can the function button.when_pressed be used twice on the same script?
if not, how can I re-initialize the button?

Please find a test code below :

import RPi.GPIO as GPIO
from gpiozero import Button

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
button = Button(21)
status = 0

def action1():
    print("Action 1")
    status = 1
    
def action2():
    print("Action 2")
    status = 0

while True:
    if status == 0:
        button.when_pressed = action1
    elif status ==1:
        button.when_pressed = action2

With this test I just realized that the button.when_pressed = action2 is not active.

How can I ask the raspberry to change the event to action 2 when the button “button” is pressed.

Thank you!!!

That assignment to status inside a function is not going to affect the global variable unless you first declare you really want to use the global variable:

def action1():
    print("Action 1")
    global status
    status = 1

See the Python documentation on the global statement. The same applies to the action2 function.

For keeping state without global variables you might want to have an object that keeps the state, and call actions as methods of that object.

1 Like

I think @airtower-luna has hit on the fix! I do think you could simplify your program though.

gpiozero is intended to replace RPI.GPIO. So I’dve removed the use of GPIO. Also, you could switch state in the callback rather than use status.

E.g.:

from gpiozero import Button
from signal import pause

def action1():
    print("Action 1")
    button.when_pressed = action2
    
def action2():
    print("Action 2")
    button.when_pressed = action1

button = Button(21)
button.when_pressed = action1
pause()