TShopping

 找回密碼
 註冊
搜索
查看: 9867|回復: 0
打印 上一主題 下一主題

[教學] 如何在python檢測按键?

[複製鏈接]
跳轉到指定樓層
1#
發表於 2020-11-26 15:06:01 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
 
Push to Facebook
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 網頁設計

 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-4-26 14:14 , Processed in 0.091708 second(s), 22 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表