954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Getting an input from arrow keys.

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.

AutoPython
Junior Poster
138 posts since Sep 2009
Reputation Points: 14
Solved Threads: 18
 

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

scru
Posting Virtuoso
1,629 posts since Feb 2007
Reputation Points: 975
Solved Threads: 140
 

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

AutoPython
Junior Poster
138 posts since Sep 2009
Reputation Points: 14
Solved Threads: 18
 

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()
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

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.

AutoPython
Junior Poster
138 posts since Sep 2009
Reputation Points: 14
Solved Threads: 18
 

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.

jorlittl
Newbie Poster
1 post since Dec 2009
Reputation Points: 10
Solved Threads: 0
 

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.

AutoPython
Junior Poster
138 posts since Sep 2009
Reputation Points: 14
Solved Threads: 18
 

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.

Szepi
Newbie Poster
3 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You