如何以左箭头键输入?

时间:2010-11-17 13:17:23

标签: python

我希望将左右箭头键作为输入之一。 我怎么才能得到它?有什么办法吗?

3 个答案:

答案 0 :(得分:6)

使用Tkinter,您可以执行以下操作....我在网上找到了它

# KeyLogger_tk2.py
# show a character key when pressed without using Enter key
# hide the Tkinter GUI window, only console shows

try:
   # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def key(event):
"""shows key or tk code for the key"""
    if event.keysym == 'Escape':
        root.destroy()
    if event.char == event.keysym:
     # normal number and letter characters
        print( 'Normal Key %r' % event.char )
    elif len(event.char) == 1:
      # charcters like []/.,><#$ also Return and ctrl/key
        print( 'Punctuation Key %r (%r)' % (event.keysym, event.char) )
    else:
      # f1 to f12, shift keys, caps lock, Home, End, Delete ...
        print( 'Special Key %r' % event.keysym )


root = tk.Tk()
print( "Press a key (Escape key to exit):" )
root.bind_all('<Key>', key)
# don't show the tk window
root.withdraw()
root.mainloop()

答案 1 :(得分:2)

你可以用ncurses来做到这一点。与TkInter不同,X11不是必需的。

#! /usr/bin/python

import curses

screen = curses.initscr()
try:
    curses.noecho()
    curses.curs_set(0)
    screen.keypad(1)
    screen.addstr("Press a key")
    event = screen.getch()
finally:
    curses.endwin()

if event == curses.KEY_LEFT:
    print("Left Arrow Key pressed")
elif event == curses.KEY_RIGHT:
    print("Right Arrow Key pressed")
else:
    print(event)

答案 2 :(得分:0)

这可以通过以下方式实现:

Curses Urwid PyGame

Tkinter位于标准库中。