boppreh / keyboard

Hook and simulate global keyboard events on Windows and Linux.
MIT License
3.74k stars 432 forks source link

How to activate count down with hotkey while stop that count down with another hotkey? #620

Open mywingdx0122 opened 8 months ago

mywingdx0122 commented 8 months ago

I want to register 2 hotkeys, such as "1" and "2". Press 1 to activate count down. While in counting down process, press 2 to interrupt the count down.

I'd like to know how to do this task?

Below is my code, but it does not work, press 2 will not stop the counting down.

Please help me, thanks in advance.

Code

COUNTING_DOWN_STOP_FLAG = False

def countDown():
    global COUNTING_DOWN_STOP_FLAG
    COUNTING_DOWN_STOP_FLAG = False
    for i in range(10):
        if COUNTING_DOWN_STOP_FLAG:
            print("Interrupted!")
            break
        sleep(1)
        print(10-i)

def stopDown():
    global COUNTING_DOWN_STOP_FLAG
    COUNTING_DOWN_STOP_FLAG = True

def try1():
    keyboard.add_hotkey("1", countDown)
    keyboard.add_hotkey("2", stopDown)
    keyboard.wait()

if __name__ == '__main__':

    try1()

Output