在执行其他代码时不断检查按钮按下?

时间:2018-05-24 20:15:28

标签: python

我需要能够通过按下按钮来停止机器人。 我已经做了概念验证,我可以通过按下按钮停止程序,但是,我只知道如何一次做一件事。

以下是我所做的代码:

buttons = Button()
while buttons.backspace != True:
    time.sleep(.1)
else:
    #I guess I need to handle some kind of cleanup here too
    pass

这应该在其他代码运行时运行。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

在这里你有通常所说的" Interrupt",所以我们将它放在一个函数上,在守护进程线程(它总是在运行)上调用它,它会看起来像什么像这样:

from threading import Thread
buttons = Button()

def checking_interrupt():
    global buttons
    while not buttons.backspace:
        time.sleep(.1)
    else:
        #I guess I need to handle some kind of cleanup here too
        pass

Thread(target=checking_interrupt).start()

在这里我没有指明它是一个守护程序线程,但是你可以,只是在" daemon"上传递一个boolea true。在你的对象线程构造函数。

相关问题