python - 如何在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() 运行时检查按钮是否被按下?
解决方案
这是您可以尝试的方法。该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()
推荐阅读
- javascript - 显示来自 JSON 对象的嵌套复选框表单
- mysql - 如果找到行,则 MySQL 在表上相交,否则忽略
- python - 使用 Stripe 和 Django 进行定期付款
- mysql - Mysql - CASE WHEN中的多个Order By选项
- ruby - grouped_collection_select,Devise 和 Rails 5.0 自定义注册问题
- jupyter-notebook - 如何在 Google 的 Colab 中关闭并重新打开正在运行的笔记本?
- python-3.x - Pandas Dataframe 上的向量函数
- sql-server - TSQL Openquery 未创建临时表
- android - 如何检测应用程序正在退出?
- vba - Excel VBA在代码快速修复中选择列号问题?