Home > Software engineering >  How do I make python execute a function when a certian key is pressed?
How do I make python execute a function when a certian key is pressed?

Time:10-29

I am currently using Visual Studio Code as my IDE, and I have been trying to figure out how to make it in my scripts where if a certian key -such as "l" for our example- was pressed, the script would trigger a block of code that executed a function - such as the print("Ayy you pressed a key! good job!") function. I was wondering if anyone could tell me how to do that, or how to make the import keyboard work. Thanks!

CodePudding user response:

you can use keyboard library ,Try this :

  import keyboard
    
    while True:
        if keyboard.read_key() == "p":
            myfunction() 

CodePudding user response:

As answered in other questions, responding to a key press involves dealing with events.

Each key press triggers/ emits an event. There are couple of library that deals with events and in particular keyboard events.

modules keyboard and getKey are worth exploring. and to a straightforward answer, refer above answer.(just dont want to repeat, credit to him)

  • Related