英文:
Listen for keyboard shortcut ESC + ESC then run some code
问题
我想监听键盘快捷键ESC + ESC
,然后运行一些代码。我的意思是,如果用户按两次ESC
键,那么应该执行一些代码。
我尝试了以下代码,但它不起作用:
from pynput import keyboard
pressed = set()
def run(s):
if (s == "switch"):
print("Hello World!")
def on_press(key):
pressed.add(key)
print(pressed)
if (key == keyboard.Key.esc and len(pressed) == 2):
run("switch")
def on_release(key):
if key in pressed:
pressed.remove(key)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
请使用最适合我的目的的库帮助我。
英文:
I want to listen for the keyboard shortcut ESC + ESC
and then run some code. What I mean is that, if the user presses the ESC
key twice, then some code should get executed.
I tried the following code, but it doesn't work:
from pynput import keyboard
pressed = set()
def run(s):
if (s == "switch"):
print("Hello World!")
def on_press(key):
pressed.add(key)
print(pressed)
if (pressed == 27):
print("Hello World!")
def on_release(key):
if key in pressed:
pressed.remove(key)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
Please help me using the library that best serves my purpose.
答案1
得分: 2
以下是您要翻译的代码的部分:
import time
from pynput import keyboard
class DoubleEscapeListener:
def __init__(self):
self.pressed = set()
self.last_esc_time = 0
self.double_press_threshold = 0.5 # 时间内必须按两次ESC键。
def run(self):
print("Hello World!")
def on_press(self, key):
if key == keyboard.Key.esc:
current_time = time.time()
if current_time - self.last_esc_time < self.double_press_threshold:
self.run()
self.last_esc_time = current_time
def on_release(self, key):
if key in self.pressed:
self.pressed.remove(key)
def listen(self):
with keyboard.Listener(on_press=self.on_press, on_release=self.on_release) as listener:
listener.join()
if __name__ == "__main__":
listener = DoubleEscapeListener()
listener.listen()
此代码将在双击ESC键的double_press_threshold
时间内运行run
方法。您可以根据需要调整此阈值。
英文:
import time
from pynput import keyboard
class DoubleEscapeListener:
def __init__(self):
self.pressed = set()
self.last_esc_time = 0
self.double_press_threshold = 0.5 # Time within which two ESC keys must be pressed.
def run(self):
print("Hello World!")
def on_press(self, key):
if key == keyboard.Key.esc:
current_time = time.time()
if current_time - self.last_esc_time < self.double_press_threshold:
self.run()
self.last_esc_time = current_time
def on_release(self, key):
if key in self.pressed:
self.pressed.remove(key)
def listen(self):
with keyboard.Listener(on_press=self.on_press, on_release=self.on_release) as listener:
listener.join()
if __name__ == "__main__":
listener = DoubleEscapeListener()
listener.listen()
This code will run the run
method when the ESC
key is pressed twice within the double_press_threshold
time. You can adjust this threshold according to your needs.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论