python 3有沒有辦法識別按鍵?例如,如果用戶按下向上箭頭,程序會做一件事,而如果按下向下箭頭,程序會做其他事情。識別Python中按鍵的代碼3
我不是指用戶必須在按鍵之後按下輸入的input()函數,我的意思是程序在某處按鍵時識別按鍵的位置。
這個問題太混亂了嗎?的xD
python 3有沒有辦法識別按鍵?例如,如果用戶按下向上箭頭,程序會做一件事,而如果按下向下箭頭,程序會做其他事情。識別Python中按鍵的代碼3
我不是指用戶必須在按鍵之後按下輸入的input()函數,我的意思是程序在某處按鍵時識別按鍵的位置。
這個問題太混亂了嗎?的xD
我想這是一個GUI程序,
如果使用內置的GUI模塊Tkinter的,可以使用綁定的功能連接到一個按鍵。
main.bind('<Up>', userUpkey)
其中userUpKey是在當前範圍中定義的函數。
Python有一個keyboard模塊有很多功能。你可以在兩個使用它殼牌和控制檯。 安裝它,也許用這個命令:
pip3 install keyboard
然後使用它的代碼,如:
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('up'): #if key 'up' is pressed.You can use right,left,up,down and others
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
你可以將其設置爲多個按鍵檢測:
if keyboard.is_pressed('up') or keyboard.is_pressed('down') or keyboard.is_pressed('left') or keyboard.is_pressed('right'):
#then do this
你也可以做例如:
if keyboard.is_pressed('up') and keyboard.is_pressed('down'):
#then do this
它也檢測整個Windows的關鍵。
謝謝。
謝謝你的回答(我實際上並沒有編寫一個程序,這只是一個普通的查詢),但是你知道它是否可以在命令行(而不是GUI)中使用嗎? –
我會看着詛咒。我沒有親自使用它,所以我不會嘗試一個例子。 – tink3r