Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

if statement - Python Code that returns true while key is pressed down false if release?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...