【问题标题】:Python while loop won't stop even when condition not met即使不满足条件,Python while循环也不会停止
【发布时间】:2026-02-14 17:05:01
【问题描述】:

在下面代码的底部,当unreadfalse 时,我设置了一个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?

标签: python loops scope


【解决方案1】:

您需要在handleBtnPress() 函数中声明unread 全局。否则,将在函数范围内创建一个新的unread 变量,而外部的变量不会改变。

def handleBtnPress():
    global unread   # without this, the "unread" outside the function won't change
    unread = False

【讨论】:

    【解决方案2】:

    一旦循环结束并且条件为假,循环总是会结束。

    这里的问题是,处理程序中的unread是一个局部变量;它不是指全局,因此永远不会设置全局。

    你必须说 unread 在改变它之前是全局的:

    def handleBtnPress():
        global unread
        unread = False
        . . . 
    

    【讨论】:

      最近更新 更多