简体   繁体   English

按下certian键时,如何让python执行函数?

[英]How do I make python execute a function when a certian key is pressed?

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.我目前正在使用 Visual Studio Code 作为我的 IDE,并且我一直试图弄清楚如何在我的脚本中制作它,如果按下了一个证书键 - 例如我们示例中的“l” - ,脚本将触发一个块执行函数的代码 - 例如 print("Ayy you press a key!干得好!") 函数。 I was wondering if anyone could tell me how to do that, or how to make the import keyboard work.我想知道是否有人可以告诉我如何做到这一点,或者如何使导入键盘工作。 Thanks!谢谢!

you can use keyboard library ,Try this :你可以使用键盘库,试试这个:

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

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.模块keyboardgetKey值得探索。 and to a straightforward answer, refer above answer.(just dont want to repeat, credit to him)和一个简单的答案,参考上面的答案。(只是不想重复,归功于他)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python) 当按下按钮时,如何使 tkinter 出现? - python) How do I make tkinter appear when a button is pressed? 在将文本输入文本小部件后按Enter键时如何执行回调? - How do I execute a callback when the Enter key is pressed after entering text into a Text widget? 我如何做到在按下一个键并释放另一个键的同时发生动作? (pygame的/蟒) - How do I make it so that while a key is pressed and another key is released an action occurs? (Pygame/python) 按下键时不确定地执行python代码 - Execute python code indefinetly when key is pressed 如何使 function 重复,直到使用 pynput 在 python 上按下特定键? - How can I make a function repeat until a specific key is pressed on python with pynput? IDLE Python - 如何在按下键时执行循环? - IDLE Python - How to make it so when a key is pressed, the loop runs? 如何让 Turtle 等待按键 - How do I make Turtle to wait for a pressed key 在python中按下键盘上的“ enter”键时,如何设置特定的动作 - How do I set a specific action to happen when the “enter” key on my keyboard is pressed in python 按下按钮时,如何使按钮的名称传递给函数? - How do I make a button pass its name to a function, when it is pressed? 如果在 kivy python 中按下一个键(回车),则执行一个函数 - Do a function if a key(enter) is pressed in kivy python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM