运行 python 中的程序时如何检查按钮是否被按下

How to check if a button is pressed while running a program in python

我想在 Python 中 运行 一个程序,同时还要检查 整个 时间是否按下了按钮(物理类型) .该程序看起来像这样:

import stuff

a = True

def main():
        important stuff which takes about 10 seconds to complete

while True:
        if a == True:
                main() 
                #at the same time as running main(), I also want to check if a button
                #has been pressed. If so I want to set a to False

我可以在 main 完成后检查按钮是否被按下,但这意味着我必须在 python 检查按钮是否被按下(或按住按下按钮)。

如何让 python 检查按钮是否被按下 main() 是 运行ning?

您可以尝试以下方法。 main 函数每秒打印一个数字,您可以通过键入“s”+ Enter 键来中断它:

import threading
import time

a = True

def main():
    for i in range(10):
        if a:
            time.sleep(1)
            print(i) 

def interrupt():
    global a # otherwise you can only read, and not modify "a" value globally
    if input("You can type 's' to stop :") == "s":
        print("interrupt !")
        a = False


t1 = threading.Thread(target=main)
t1.start()
interrupt()