8

New to python here and using the curses import. I want to detect key combinations like ALT+F and similar. Currently, I am using getch() to receive a key and then printing it in a curses window. The value does not change for F or ALT+F. How can I detect the ALT key combinations?

import curses

def Main(screen):
   foo = 0
   while foo == 0: 
      ch = screen.getch()
      screen.addstr (5, 5, str(ch), curses.A_REVERSE)
      screen.refresh()
      if ch == ord('q'):
         foo = 1

curses.wrapper(Main)
chrki
  • 6,143
  • 6
  • 35
  • 55
wufoo
  • 13,571
  • 12
  • 53
  • 78

1 Answers1

6

Try this:

import curses

def Main(screen):
   while True:
      ch = screen.getch()
      if ch == ord('q'):
         break
      elif ch == 27: # ALT was pressed
         screen.nodelay(True)
         ch2 = screen.getch() # get the key pressed after ALT
         if ch2 == -1:
            break
         else:
            screen.addstr(5, 5, 'ALT+'+str(ch2))
            screen.refresh()
         screen.nodelay(False)

curses.wrapper(Main)
Wojciech Walczak
  • 3,419
  • 2
  • 23
  • 24
  • 2
    OP, ^ this is the best method I've seen. Otherwise, you may not like what they say, but checkout http://stackoverflow.com/questions/9750588/how-to-get-ctrl-shift-or-alt-with-getch-ncurses Good luck! – wbt11a Mar 12 '14 at 20:25
  • Perhaps getch() is not the correct function call to use. I recall it being quite limited for some things in the C language. Perhaps a better question would be how to read raw scan codes... Also, the example does not seem to work pasted in. Hmm.. – wufoo Mar 13 '14 at 17:27
  • Actually the code works fine pasted in. My mistake. I was expecting it to print all keys, not just ALT+ combinations. Thanks! – wufoo Mar 13 '14 at 17:41
  • 1
    Update: a while after using this code, I noticed pressing the [ESC] key would generate a 1 second delay. I needed to call os.environ['ESCDELAY'] = "25" prior to entering curses.wrapper. – wufoo Mar 26 '14 at 19:56