如果按下某个键,我如何才能真正中断一段时间?[Python] [英] How can I make a while True break if certain key is pressed? [Python]
问题描述
我的脚本使 while 为 True:从按下 F4 开始,但我希望它在按下 F2 时停止,我该怎么做?
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?
我正在尝试此操作(使用 pyhook)但不起作用...
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
推荐答案
您不会在循环中更改 event
,因此您不会期望 event.KeyID
之前是 115 时突然变成 113.
You're not changing event
within your loop, so you wouldn't expect event.KeyID
to suddenly become 113 when it was 115 previously.
您可能会做的是,在处理 F4 按键时,启动一个计时器,每两秒执行一次 selectAndCopy.当您通过 F2 键击获得另一个事件时,终止计时器.
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.
它可能看起来像这样:
def onKeyboardEvent(event):
if event.KeyID == 115: #F4
startTimer(doTimer, 2)
if event.KeyID == 113:
stopTimer()
def doTimer():
selectAndCopy(468,722)
getClipboard()
您必须提供或查找 startTimer()
和 stopTimer()
的实现.
You would have to provide or find implementations of startTimer()
and stopTimer()
.
这篇关于如果按下某个键,我如何才能真正中断一段时间?[Python]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!