我制作了一个for
循环,该循环将在使用 gpiozero 按下按钮时生成时间表,并希望长按退出循环。
最初我以为我可以制作一个带有 a 的函数,break
它可以通过长按退出循环,但是由于在break
循环之外,我得到一个语法错误,不管我期望它会被解释为退出函数而不是循环该函数被调用。
另一个想法是制作类似的东西 - 当 false 退出所有循环 - 并且循环中的命令for
将该条件切换为 false。这不是我在任何教程中涵盖的内容,并且不确定我会搜索哪些术语来了解是否可以做到这一点。
我怎样才能做到这一点?
import gpiozero
import time
from signal import pause
button = gpiozero.Button(2, hold_time=0.5)
#button wired to gpio 2, long press activates after .5 seconds
a = int(input('Choose a number: '))
print('Press the button to do times tables.')
print('Hold the button to tell maths to quit.')
def cont():
print('quit maths')
#this is where I initially tried to use a break
for x in range(1, 13):
button.wait_for_press()
button.when_held = cont
button.wait_for_release()
print('7 x', x, '=', x * a, flush=True)
pause()