Question

I'm building a curses module and using KEY_DOWN to check if a arrow down key is pressed.

But, I get a Name error saying KEY_DOWN is not defined.

if value == KEY_DOWN:

NameError: global name 'KEY_DOWN' is not defined

No correct solution

OTHER TIPS

Good day!

You have to do:

if value == curses.KEY_DOWN:

for it to work.

Hope this works!!!
But if this doesn't work show us your code (so we can analyze it)

To follow up to mvndaai's answer, if you want to detect arrow keys in Python, you have to AND together the three different ASCII values. For example:

    key = getch()
    if key == (27 and 91 and 65):   #27 is ESC, 91 is [, and 65 is A
        print("Up key pressed!")
    if key == (27 and 91 and 66):
        print("Down key pressed!")
    if key == (27 and 91 and 67):
        print("Right key pressed!")
    if key == (27 and 91 and 68):
        print("Left key pressed!")

I am not sure why the yave a gloabl named KEY_DOWN, but if you want a key down, you need to do 3 getchs. Warning, the first getch is the same as an ESC. That means you either make sure it doesn't close on ESC or do a work around like I did below. I also included a chart of what you will get as a getch for each key.

Key
ESC
UP
DOWN
RIGHT
LEFT
getch
27
27
27
27
27
getch
 
[
[
[
[
getch
 
A
B
C
D

Which means that when you hit any Arrow key and you are triggering a ESC.

In ruby I tried a work around of checking for 27, then doing a quick timeout on another getch. If that gets a [ it is an arrow or something else, otherwise it is the escape key. Here is my ruby code:

def read_key
  ch = getch
  return check_escape_chars if ch == 27
  ch
end

def check_escape_chars
  require 'timeout'
  begin
    Timeout.timeout(0.0001) {getch}
    case getch
    when "A"; return "UP"
    when "B"; return "DOWN"
    when "C"; return "RIGHT"
    when "D"; return "LEFT"
    end
  rescue Timeout::Error
    return "ESC"
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top