[英]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.模块keyboard
和getKey
值得探索。 and to a straightforward answer, refer above answer.(just dont want to repeat, credit to him)和一个简单的答案,参考上面的答案。(只是不想重复,归功于他)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.