I have the following code, and I cannot figure out how to make when_pressed and when_released work. The callback functions just do not run to the press and release.

On the other hand, properties such as is_pressed do work as expected.



    def function1(self, gpio_button, held_duration):

        ds = DoorSound()

        gpio_button.when_pressed = ds.start_door_sound
        # gpio_button.when_pressed = lambda: ds.start_door_sound() # <-- I have also tried this alternative
        gpio_button.when_released = ds.stop_door_sound
        # gpio_button.when_released = lambda: ds.stop_door_sound()

        do_loop = True
        while do_loop:
            # do more stuff and at some point set do_loop to False


DoorSound is defined as follows:

class DoorSound(object):

    def __init__(self):
        self.file_path = 'sounds/door_sound.mp3'
        self.pygame_door = pygame.mixer

    def start_door_sound(self):
        print('Start door sound!')

    def stop_door_sound(self):
        print('Stop door sound!')

I also tried:

  • start_door_sound and stop_door_sound functions inside the MyDoor class
  • the following simple function, that when it is called directly, instead of as a callback, works. And not trying to stop it.


def door_sound(self):

    """Reproduce a DOOR SOUND"""

    print('♩ ♪ ♫ ♬  Door sound ♩ ♪ ♫ ♬')

    while pygame.mixer.music.get_busy() == True:

but none of them made any difference.

The text inside the functions is never printed, so I guess the problem is that somehow the callback function is never called.

I read somewhere that when_pressed and when_released functions might not work well inside loops, but unfortunately, the documentation is not very extensive so I don't know if that might be the case. In any case, function1 runs inside some while loops.

Does anybody know what the problem is?

  • I'd try and minimise this as much as possible. It doesn't look like you need any of those classes. Also try removing the sleep as that might interfere. And it won't actually make a difference being there at the end. – ben_nuttall Jun 12 at 19:41
  • An alternative approach could be to switch to a loop that waits for the button to be pressed using btn.wait_for_press() instead of using callbacks. – ben_nuttall Jun 12 at 19:42
  • @ben_nuttall, thanks for the tips. I will give it a try. Regarding the wait_for_press function, would that make the music play as long as the button is pressed and stop it as soon as the button is released or when a timeout is reached? – J0ANMM Jun 13 at 20:13
  • By removing sleep it seems to be working most of the time. However, I made sure I removed all of them from my code and sometimes it randomly does not work... – J0ANMM Jun 17 at 11:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.