0

while this code succeeds:

def press_on():
            print('press')

        HWButs = gpiozero.Button(21)
        HWButs.when_pressed = MainApp.init_buts.press_on

inside a class, pressing the button does not execute press_on

(irrelevant code is croped out ):

class MainApp:
    def __init__(self,master, pins,ip):
        self.frame1= LabelFrame(master,text='Hardware Display',padx=10, pady=10)
        self.frame2= LabelFrame(master, text="Buttons")
        self.frame1.grid(row = 0, column= 0, padx=20, pady=20)
        self.frame2.grid(row = 1, column = 0)

        self.HardWare = RemRelay(ip, pins)
        self.GUI = RemRelay_GUI(self.frame1,pins)
        self.SFButs = SwitchButtons(self, self.frame2,len(pins))
        #self.HWButs = ButtonSwitchRel(self, input_gpioPins,output_gpioPins)
        self.update_gui()
        self.init_buts()

    def init_buts(self):  ## here is where but is defined
        def press_on():
            print('press')

        HWButs = gpiozero.Button(21)
        HWButs.when_pressed = MainApp.init_buts.press_on


    def update_gui(self):
        self.GUI.get_state(self.HardWare.get_state())
        root.after(500,self.update_gui)



root = Tk()
output_gpioPins = [4,22,6,26]
input_gpioPins = [3,21,5,27]
ip = '192.168.2.113'
App = MainApp(root, output_gpioPins, ip )
root.mainloop()
0

Suprisingly, the answer lies with preceding self. for all pigpio fuctions. this is how it was tested: "A" class was created, with a Button,LED, and an OutPut device (Relay )button press, all 3 were activated correctly.

from gpiozero import LED, Button
from signal import pause
from gpiozero import OutputDevice
from gpiozero.pins.pigpio import PiGPIOFactory
from time import sleep
import gpiozero

class A:
    def __init__(self):
        factory = PiGPIOFactory(host='192.168.2.113')
        self.Relay= OutputDevice(13, pin_factory=factory,initial_value=False)
        self.led = LED(17)
        self.button = Button(21)
        self.led.source = self.button.values
        self.button.when_released = self.switchoff
        self.button.when_pressed = self.switchon


    def switchon(self):
        self.Relay.on()

    def switchoff(self):
        self.Relay.off()


Rel = A()
pause()

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.