简体   繁体   中英

How can I make a while True break if certain key is pressed? [Python]

My script make a while True: begin with the F4 pressed, but I want it to stop when the F2 is pressed, how can I do it?

I'm trying this (using pyhook) but doesn't work...

def onKeyboardEvent(event):
    if event.KeyID == 115:      #F4
        while True:
            selectAndCopy(468,722)
            getClipboard()
            time.sleep(2)
            if event.KeyID == 113:
                break
    return True

You're not changing event within your loop, so you wouldn't expect event.KeyID to suddenly become 113 when it was 115 previously.

What you might do is, on handling an F4 keypress, start a timer that does the selectAndCopy every two seconds. When you get another event with an F2 keystroke, kill the timer.

It could look something like this:

def onKeyboardEvent(event):
    if event.KeyID == 115:      #F4
        startTimer(doTimer, 2)
    if event.KeyID == 113:
        stopTimer()

def doTimer():
    selectAndCopy(468,722)
    getClipboard()

You would have to provide or find implementations of startTimer() and stopTimer() .

Make key event which

  1. change variable True with F4 and if the variable is still True do new timer event for example in Tkinter

    mylabel.after(2000, process) # process is the function to do your stuff

  2. change variable False with F2 and cancels the timer (after_cancel)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM