Python Forum

Full Version: curses library
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there,
i am new in programming and i am using a rpi 3 b with python 2.7 to control a couple of servo motors but i have a couple of problems with my code.
I want to use keyboard inputs to activate my gpio's.
I have done some research and i found a library that can help me do that but i am getting all kind of bugs. Basically i want the keyboard controls i type to go in a variable (i use raw_input). I dont know though how to write the keyboard keys in the code. For example i know that up arrow is KEY_UP, down arrow is KEY_DOWN etc. Is there any way that i can see how to express each key to my code?
Or any different idea on how to make this work ?
Thanks in advance
First, you should be using python 3.7. That's the latest version.
Python 2.7 dies in less that 10 months.
That being said, please:
  • Show code
  • Show errors complete and unmodified
  • Use BBcode tags
Something I found on the web a long time ago. There has to be other key capture programs as well.

import curses

arrow_keys = {curses.KEY_UP:'up arrow',
              curses.KEY_DOWN:'down arrow',
              curses.KEY_LEFT:'left arrow',
              curses.KEY_RIGHT:'right arrow'}

## open a window/screen object
stdscr = curses.initscr()
curses.cbreak()
stdscr.keypad(1)

stdscr.addstr(0,10,"Hit 'q' to quit ")
stdscr.refresh()

key = ''
while key != ord('q'):
    key = stdscr.getch()
    stdscr.addstr(20,25,"     ")
    stdscr.addch(20,25,key)
    stdscr.refresh()

    if key in arrow_keys:
       stdscr.addstr(18, 20, arrow_keys[key])
    else:
       stdscr.addstr(18, 20, "              ")

curses.endwin()