Skip to content
Sign upLog in
← Back to Community

Arrow Keys In Python

Profile icon
JWZ6Hacker

Hello Everyone!

Welcome back to another tutorial!

I usually try to make tutorials not in Python. I think that I can let this one slide in, though.

Contents

  • Curses (Python Module)
  • Detecting The Keys
  • Final Code
  • Ending

Curses (Python Module)

Do not be afraid! This module won't actually curse you. Anyways, to import the module, use import curses. Everytime you use curses, you must do curses.initscr(). You can turn it into a variable to save time. That will show the screen.

Keypad

If you do not use the keypad, you would see some weird computer codes. You must use curses.initscr().keypad(). What goes inside the () is either 1 (true) or 0 (false). In order to start the arrow keys, use:

# Importing The Curses Module import curses # Making The Screen screen = curses.initscr() # Allowing The Keypad screen.keypad(1)

Detecting The Keys

Using input will not work. You must use curses.initscr().getch(). That's long, right? Anyways, once you have done that, you have the key codes. For the up arrow key, do curses.KEY_UP. For the down arrow key, use curses.KEY_DOWN. I think you know what the other 2 arrow key codes are. You might possibly have:

arrow_key = curses.initscr().getch() if arrow_key == curses.KEY_UP: print("Up") else: print("Not up")

Final Code

import curses arrow_key = curses.initscr().getch() if arrow_key == curses.KEY_UP: print("Up") elif arrow_key == curses.KEY_DOWN: print("Down") elif arrow_key == curses.KEY_RIGHT: print("Right") elif arrow_key == curses.KEY_LEFT: print("Left") else: print("Not an arrow key")

Ending

Anyways, I hope this tutorial helped you. Please leave an upvote if it did. That's it for now...

Bye

P.S Check out my other arrow key tutorials:
Javascript and C++

Voters
Profile icon
Austin0605
Profile icon
EshaanAhuja
Profile icon
EricWells
Profile icon
JWZ6
Profile icon
SilvermoonCat
Profile icon
50ShadesofRay
Profile icon
Bunnytoes
Comments
hotnewtop
Profile icon
IceWing099

lol

Profile icon
JWZ6

@IceWing099
ye how u find this tho

Profile icon
[deleted]

"curses" lol

Profile icon
JWZ6
Profile icon
Bunnytoes

good job

Profile icon
JWZ6
Profile icon
Bunnytoes

@JWZ6
hey could you check out my tutorial with special animations, here it is tutorial

Profile icon
JWZ6
Profile icon
50ShadesofRay

Thanks this was really helpful

Profile icon
JWZ6