我想在 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條經(jīng)驗 獲得超9個贊
您可以嘗試以下方法。該main功能每秒打印一個數(shù)字,您可以通過輸入“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()
添加回答
舉報
0/150
提交
取消