【发布时间】:2026-02-14 17:05:01
【问题描述】:
在下面代码的底部,当unread 为false 时,我设置了一个while 循环停止,这发生在按下按钮后的def 内部(这是在RPi 上)。一切都在执行中成功。我有 cmets 详细说明,因为这样更容易解释。我对python还很陌生,如果这是一个简单的错误,我深表歉意。
from customWaveshare import *
import sys
sys.path.insert(1, "../lib")
import os
from gpiozero import Button
btn = Button(5) # GPIO button
unread = True # Default for use in while loop
def handleBtnPress():
unread = False # Condition for while loop broken, but loop doesn't stop
os.system("python displayMessage.py") # this code runs, and then stops running,
while unread is not False:
os.system("echo running") # this is printed continuously, indicating that the code never stops even after the below line is called successfully
btn.when_pressed = handleBtnPress # Button pushed, go to handleBtnPress()
感谢您的所有帮助!
【问题讨论】:
-
两个问题:1)你没有在循环中调用
handleBtnPress,你只是将函数分配给一个变量。 2) 函数设置的是局部变量,而不是全局变量。 -
@Barmar 我认为对于 1,它是由任何系统调用的?看起来它在外部按钮上设置了一个处理程序。
-
您不必在循环中分配按钮的
when_pressed属性。只需执行一次,它会在按下按钮时调用该函数。 -
如果您不熟悉范围界定,您可能需要查看Short description of the scoping rules?