I want to get the left and right arrow key as a one of the input. How can i get it? Is there any way?
Asked
Active
Viewed 1.7k times
5
-
Please define "input", input on the console? On a window? If so which gui framework was used to created the window? – Ivo Wetzel Nov 17 '10 at 13:29
-
I want to get input on a window. It consists of some text field entries, if I press left arrow Key means the cursor have to move one field back. That is the thing I need. Well I have used GLADE (gtk-builder) and python to create the window. – gnubala Nov 21 '10 at 06:01
-
terminal script -- I apologize for not clarifying earlier. My work never involves GUIs so it is not on my mind – daniel Feb 01 '13 at 00:23
3 Answers
6
Using Tkinter you can do the following .... I found it on the net
# 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()
-
3that is a substantial amount of complexity if the goal is a small, minimal script. Is there seriously no one/two line solution? – daniel Jan 31 '13 at 23:35
2
That's how you can do it with ncurses. Unlike TkInter, X11 is not required.
#! /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)

proski
- 3,603
- 27
- 27