本文介绍了按键检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直试图在Python程序中检测到按键.我想找到一种无需使用Tkinter,curses
或raw_input
的方法.这就是我要去的地方:
I've been trying to get keypresses to be detected in a Python program. I want to find a way to do this without using Tkinter, curses
, or raw_input
. Here's what I'm going at:
while True:
if keypressed==1:
print thekey
有人知道这怎么可能吗?
Does anyone know how this is possible?
推荐答案
Python具有 键盘 模块具有许多功能.安装它,也许使用以下命令:
Python has a keyboard module with many features. Install it, perhaps with this command:
pip3 install keyboard
然后在类似以下代码中使用它:
Then use it in code like:
import keyboard #Using module keyboard
while True:#making a loop
try: #used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('a'): #if key 'a' is pressed
print('You Pressed A Key!')
break #finishing the loop
else:
pass
except:
break #if user pressed other than the given key the loop will break
您可以设置多个按键检测:
You can set multiple Key Detection:
if keyboard.is_pressed('a') or keyboard.is_pressed('b') or keyboard.is_pressed('c'):
#then do this
这篇关于按键检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!