Okay, I'm trying to make a python game (not with pygame), I want it to use the arrow keys. But the thing is, I don't know how to get it to respond to the arrow keys. So here's what I want to do.

If the user presses the up arrow key set the variable 'direction' to up, if the press the down arrow key set direction to 'down' etc. Would this be possible? If so, how? The only thing I know is that you need to use KeyboardInterupt or something like that.

If you a using a GUI/event-driven framework, then yes, it's possible. If you are using console python, then no.

I'm perfectly fine with using tkinter. But I don't even know how to do that :( .

Here is an example of a Tkinter key logger ...

# KeyLogger_tk2.py
# show a character key when pressed without using Enter key
# hide the Tkinter GUI window, only console shows

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def key(event):
    """shows key or tk code for the key"""
    if event.keysym == 'Escape':
        root.destroy()
    if event.char == event.keysym:
        # normal number and letter characters
        print( 'Normal Key %r' % event.char )
    elif len(event.char) == 1:
        # charcters like []/.,><#$ also Return and ctrl/key
        print( 'Punctuation Key %r (%r)' % (event.keysym, event.char) )
    else:
        # f1 to f12, shift keys, caps lock, Home, End, Delete ...
        print( 'Special Key %r' % event.keysym )


root = tk.Tk()
print( "Press a key (Escape key to exit):" )
root.bind_all('<Key>', key)
# don't show the tk window
root.withdraw()
root.mainloop()

Thank you! you gave me much more then I asked for, as a result I'll be able to use much more then just the arrow keys.

The Tkinter code has been working great for me- However, I was wondering if there was a way to pass additional variables into the key function. I also haven't been able to get it to work without showing the tk window.

If you're using windows, I don't suggest you use that any more, use this:

from msvcrt import getch
from threading import Thread

### BACKGROUND CODE

def KeyCheck():
    global Break_KeyCheck
    Break_KeyCheck = False
    
    while Break_KeyCheck:
        base = getch()
        if base == '\xe0':
            sub = getch()
            
            if sub == 'H':
                key = 'UP_KEY'

            elif sub == 'M':
                key = 'RIGHT_KEY'

            elif sub == 'P':
                key = 'DOWN_KEY'

            elif sub == 'K':
                key = 'LEFT_KEY'
                   
Thread(target = KeyCheck).start()

### BACKGROUND CODE

It will constantly set the variable 'key', to whatever arrow key you press. If you wish to stop the background code at any time just do 'Break_KeyCheck = True' if you want to start it again do 'Break_KeyCheck = False'. I hope that helps. This also solves the issue, if you click on the screen it stops working. This is more simpler, so you should be able to use this to solve your issue.

Edited 6 Years Ago by AutoPython: n/a

The code does not work on my Mac. If I comment out the withdrawing of the root window then it works fine as long as I make the root window focused. Tested for Python 3.2.2 and Python 2.7.2.

This can be done in the console. Don't give answers when you don't know them. There is a module: readline. It is default. Like metasploit, we can even import from files or manually add the lines ourselves

@The_6 This thread is 6 years old, I guess AutoPython moved to another project since then. Please don't revive old threads, start new ones instead !

This question has already been answered. Start a new discussion instead.