[英]Python 3 pressed key detect
在 Python 3 中是否有內置的支持方法來檢測按下了哪個鍵?沒有第三方庫?
我在谷歌搜索,大多數答案都使用外部庫。 有沒有辦法使用純 python 來做到這一點?
我得到了一些答案,我不知道所有導入的庫是否都是內置 python,但它工作得很好
#!/usr/bin/python3
# adapted from https://github.com/recantha/EduKit3-RC-Keyboard/blob/master/rc_keyboard.py
import sys, termios, tty, os, time
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
button_delay = 0.2
while True:
char = getch()
if (char == "p"):
print("Stop!")
exit(0)
if (char == "a"):
print("Left pressed")
time.sleep(button_delay)
elif (char == "d"):
print("Right pressed")
time.sleep(button_delay)
elif (char == "w"):
print("Up pressed")
time.sleep(button_delay)
elif (char == "s"):
print("Down pressed")
time.sleep(button_delay)
elif (char == "1"):
print("Number 1 pressed")
time.sleep(button_delay)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.