为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

繁星点点滴滴 2023-09-19 14:06:00
我想在 Python 中运行一个程序,同时还始终检查是否按下了按钮(物理类型)。该程序看起来像这样:import stuffa = Truedef main():        important stuff which takes about 10 seconds to completewhile 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() 运行时检查按钮是否被按下?
查看完整描述

1 回答

?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

您可以尝试以下方法。该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()


查看完整回答
反对 回复 2023-09-19
  • 1 回答
  • 0 关注
  • 56 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信