Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

python - How to use gpiozero.Button.when_pressed within a class or function

I'm working on a weather station (raspberry pi) and I'm using python. I developed a program that is working, but now I decided to update my code and to structure everything (making classes etc.). But now I have encountered two problems concerning Button from gpiozero.
Firstly, when I try to assign a function to Button.when_pressed within a function or class, the function won't get called when the Button gets pressed.

Following code is just an example to keep the code as little as possible:

from gpiozero import Button
import time

number = 0
def function_that_gets_called():
    global number
    number += 1

def main():
    wind_sensor = Button(6)
    wind_sensor.when_pressed = function_that_gets_called

main()

while True:
    # Sleep, so the program doesn't exit immediately
    time.sleep(60)
    

# Do some other stuff with number

Why doesn't function_that_gets_called get called when the Button is pressed. Similarly, when I try to assign when_pressed in a class, it won't work neither.

Secondly, why do I have to use global number? Otherwise the number variable won't get changed, but is there another solution to do it in a better way?

Thank you a lot!

EDIT: Edited time.sleep(60). And I specified, what I mean by doesn't work. This is my first question here on stackoverflow, so please excuse if haven't been precise and it would be great to tell me how to improve my question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...