Python Forum
How do I read the keyboard arrow keys?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I read the keyboard arrow keys?
#1
I am trying to get a Python2 program to print the result of the up, down, left and right arrows. This sample program did that. I also want the program to exit when the escape key is pressed. I added code and it did that. But, I want it to do both at the same time. The arrow keys are three character sequences. I can access each character or the three character sequence. But, I can not combine the three characters to get the three character sequence or break the three character sequence into the individual parts. Does anyone know the solution to this problem?

Quote:import sys,tty,termios

class _Getch:

def __call__(self):
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch

def get():
inkey = _Getch()
Count = 1
while(1):
print "Count is ", Count
#Count = Count + 1
#k = inkey()
for j in range( 1, 4 ):
print "j is ", j
char = ''
#char[j-1] = inkey()
char = inkey()
#char[j-1] = inkey()
#if char[i] = esc
# exit()
print "char is ", char
if char == 'q' or char == '\x1b': # x1b is ESC
exit("Edit2")
#charlist.append(char)
#charlist[j] = char
#charlist = charlist + char
#print "charlist is ", charlist
print "Next"
#print hex(k)
#if charlist != '':break
if j == 3:
print "j == 3"
break
if charlist == '\x1b[A':
print "up"
elif charlist == '\x1b[B':
print "down"
elif charlist == '\x1b[C':
print "right"
elif charlist == '\x1b[D':
print "left"
else:
print "not an arrow key!"
#charlist.clear()
charlist = ""

def main():
for i in range(0,20):
print "i is ", i
get()

if __name__ == '__main__':
print "if __name__ == '__main__':"
Count = 1
char =[]
charlist = []
main()
#get()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Attempting to read keyboard outside of console Jimmy998 5 1,350 Nov-25-2022, 08:17 PM
Last Post: Larz60+
Thumbs Up Convert ActiveDirectory timestamp into regular one. Arrow (solved) SpongeB0B 2 1,928 Nov-02-2020, 08:34 AM
Last Post: bowlofred
  Automatically read copied text from keyboard shortcuts Ambidexter2017 10 11,170 Mar-10-2017, 01:46 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020