TShopping

標題: 如何在python檢測按键? [打印本頁]

作者: woff    時間: 2020-11-26 15:06
標題: 如何在python檢測按键?
Python有一個 keyboard   具有許多功能的模組.使用以下命令安裝它:

  1. pip3 install keyboard
複製代碼

以下代碼:

  1. import keyboard  # using module keyboard
  2. while True:  # making a loop
  3.     try:  # used try so that if user pressed other than the given key error will not be shown
  4.         if keyboard.is_pressed('q'):  # if key 'q' is pressed
  5.             print('You Pressed A Key!')
  6.             break  # finishing the loop
  7.         else:
  8.             pass
  9.     except:
  10.         break  # if user pressed a key other than the given key the loop will break
複製代碼


Curses是cli軟體的圖形API,您不僅可以檢測關键事件,還可以實現更多的功能。

此代碼將檢測按键,直到按下新行為止。

  1. import curses
  2. import os
  3. def main(win):
  4.     win.nodelay(True)
  5.     key=""
  6.     win.clear()               
  7.     win.addstr("Detected key:")
  8.     while 1:         
  9.         try:                 
  10.            key = win.getkey()         
  11.            win.clear()               
  12.            win.addstr("Detected key:")
  13.            win.addstr(str(key))
  14.            if key == os.linesep:
  15.               break           
  16.         except Exception as e:
  17.            # No input   
  18.            pass         
  19. curses.wrapper(main)
複製代碼

對於努力尋找可行答案的人来說,這是我的:pynput

  1. from pynput.keyboard import Key, Listener
  2. def on_press(key):
  3.     print('{0} pressed'.format(
  4.         key))
  5. def on_release(key):
  6.     print('{0} release'.format(
  7.         key))
  8.     if key == Key.esc:
  9.         # Stop listener
  10.         return False
  11. # Collect events until released
  12. with Listener(
  13.         on_press=on_press,
  14.         on_release=on_release) as listener:
  15.     listener.join()
複製代碼

上面的功能將print您所按的任何键,並在釋放'esc'键時開始執行操作.鍵盤文件在這裏用於更多用法。

Windows   你可以用 msvcrt   像這樣:

  
  1. import msvcrt
  2.    while True:
  3.        if msvcrt.kbhit():
  4.            key = msvcrt.getch()
  5.            print(key)   # just to show the result
複製代碼




文章出處

網頁設計,網站架設 ,網路行銷,網頁優化,SEO -
NetYea 網頁設計





歡迎光臨 TShopping (http://www.tshopping.com.tw/) Powered by Discuz! X3.2