| 
 | 
 
 
Python有一個 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('q'):  # if key 'q' is pressed 
 
 -             print('You Pressed A Key!')
 
 -             break  # finishing the loop
 
 -         else:
 
 -             pass
 
 -     except:
 
 -         break  # if user pressed a key other than the given key the loop will break
 
  複製代碼 
 
Curses是cli軟體的圖形API,您不僅可以檢測關键事件,還可以實現更多的功能。 
 
此代碼將檢測按键,直到按下新行為止。 
 
- import curses
 
 - import os
 
 - def main(win):
 
 -     win.nodelay(True)
 
 -     key=""
 
 -     win.clear()                
 
 -     win.addstr("Detected key:")
 
 -     while 1:          
 
 -         try:                 
 
 -            key = win.getkey()         
 
 -            win.clear()                
 
 -            win.addstr("Detected key:")
 
 -            win.addstr(str(key)) 
 
 -            if key == os.linesep:
 
 -               break           
 
 -         except Exception as e:
 
 -            # No input   
 
 -            pass         
 
 - curses.wrapper(main)
 
  複製代碼 
對於努力尋找可行答案的人来說,這是我的:pynput 
 
- from pynput.keyboard import Key, Listener
 
 - def on_press(key):
 
 -     print('{0} pressed'.format(
 
 -         key))
 
 - def on_release(key):
 
 -     print('{0} release'.format(
 
 -         key))
 
 -     if key == Key.esc:
 
 -         # Stop listener
 
 -         return False
 
 - # Collect events until released
 
 - with Listener(
 
 -         on_press=on_press,
 
 -         on_release=on_release) as listener:
 
 -     listener.join()
 
  複製代碼 
上面的功能將print您所按的任何键,並在釋放'esc'键時開始執行操作.鍵盤文件在這裏用於更多用法。 
 
Windows   你可以用 msvcrt   像這樣: 
 
  - import msvcrt
 
 -    while True:
 
 -        if msvcrt.kbhit():
 
 -            key = msvcrt.getch()
 
 -            print(key)   # just to show the result
 
  複製代碼 
 
 
 
文章出處 
 
網頁設計,網站架設 ,網路行銷,網頁優化,SEO - NetYea 網頁設計 
 |   
 
 
 
 |