簡體   English   中英

在Python中獲取按鍵新聞

[英]Getting Key Press Information in Python

我正在嘗試編寫一個Python程序,該程序從命令行中讀取輸入,就像輸入內置函數一樣。 我還希望能夠檢測到某些鍵的按鍵操作(例如主頁,結束,向上翻頁,向下翻頁,功能鍵等)。當按下其中一個鍵時,我想觸發一個事件(即調用映射函數)。 當按下Enter鍵時,其他鍵應放入緩沖區以返回(即,就像內置輸入一樣)。 最后,我希望它可以跨平台並在命令行上運行。

實際上,我希望能夠在輸入向下翻頁鍵時向下滾動頁面,並在按下回車鍵時仍從輸入行返回文本。

我發現許多不符合所有這些標准的解決方案:

  • 內置輸入-在輸入Enter之前不會檢測特殊鍵,也不會返回
  • 詛咒-Windows不附帶
  • msvcrt.getch-僅Windows
  • tkinter-不在命令行上運行
  • readline-無法重新映射標准導航鍵(例如home和end)。 當我綁定這些鍵時,它仍然執行vi或emacs導航功能

任何幫助,將不勝感激。

您可以在python中下載鍵盤模塊

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('a'): #if key 'a' is pressed 
            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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM