如果释放,按下键时返回true的Python代码? [英] Python Code that returns true while key is pressed down false if release?

查看:65
本文介绍了如果释放,按下键时返回true的Python代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要python中的代码,如果按下并按住某个键,则返回一个if语句为true;如果释放该键,则返回false.我希望每当按住此键时都可以执行此代码.

I need a code in python that returns an if statement to be true if a key is pressed and held down and false if it is released. I would like this code to be able to be executed whenever the key is pressed and held down.

推荐答案

在某些系统上,键盘可以在按下时重复发送按键事件,因此,使用 pynput 时,您仅需要此操作(对于按键'a')

On some systems keyboard can repeate sending key event when it is pressed so with pynput you would need only this (for key 'a')

from pynput.keyboard import Listener, KeyCode

def get_pressed(event):
    #print('pressed:', event)
    if event == KeyCode.from_char('a'):
        print("hold pressed: a")

with Listener(on_press=get_pressed) as listener:
    listener.join()

但是有时候重复是行不通的,或者需要很长的时间来重复密钥,您可以使用全局变量作为密钥来保持True/False

But sometimes repeating doesn't work or it need long time to repeate key and they you can use global variable for key to keep True/False

from pynput.keyboard import Listener, KeyCode
import time

# --- functions ---

def get_pressed(event):
    global key_a # inform function to use external/global variable instead of local one

    if event == KeyCode.from_char('a'):
        key_a = True

def get_released(event):
    global key_a

    if event == KeyCode.from_char('a'):
        key_a = False

# --- main --

key_a = False  # default value at start 

listener = Listener(on_press=get_pressed, on_release=get_released)
listener.start() # start thread with listener

while True:

    if key_a:
        print('hold pressed: a')

    time.sleep(.1)  # slow down loop to use less CPU

listener.stop() # stop thread with listener
listener.join() # wait till thread ends work

这篇关于如果释放,按下键时返回true的Python代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆