LoginSignup
13
16

More than 1 year has passed since last update.

pythonでキーボードイベント取得

Last updated at Posted at 2017-03-17

キーボードイベントを取得したい

ユーザが特定のキーを入力したときに何かを出力したい

コード

from msvcrt import getch

def select():
    #do something

def moveDown():
    #do something

def moveUp():
    #do something

def main3():
    while True:
        key = ord(getch())
        if key == 27: #エスケープ
            break
        elif key == 13: #エンター
            select()

        elif key == 224: #スペシャルキー(矢印、Fキー、ins、del、など)
            key = ord(getch())
            if key == 80: #上矢印
                moveDown()
            elif key == 72: #下矢印
                moveUp()

asciiコード対応表

(2021/11/17更新)
https://theasciicode.com.ar/ascii-control-characters/escape-ascii-code-27.html

気づいたこと

  • コマンドプロンプト上でしか反応しない(どのウィンドウ上の入力でも反応してほしかった)
  • Window OSのみ

 参考資料

13
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
16