Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

How to use getkey in Python

getkey is a Python module that allows us to capture individual keystrokes from the user without requiring them to press Enter after each key.

To understand getkey it is good to first recall the standard method for taking input from users, i.e., using the input() function.

Here is a simple program that uses input():

def main():
    name = input('Please enter your name: ')
    if name:
        first_char = name[0].upper()
        print(f'Your name starts with {first_char}')
    else:
        print('You did not enter a name.')

if __name__ == "__main__":
    main()

You can run this code like so:

Please enter your name: Kodeclik
Your name starts with K

How does this program work? It is basically an illustration of how a simple interaction with the user using the input() function will proceed. It starts by defining a main() function that encapsulates the core logic. Within this function, we prompt the user to enter their name using input(), which waits for the user to type something and press Enter. The entered name is stored in the name variable. We then use a conditional statement to check if the user actually entered a name. If they did, we extract the first character of the name using string indexing (name) and convert it to uppercase for consistency. The program then prints a message stating which letter the name starts with.

If the user didn't enter a name and just pressed Enter, we inform them that no name was entered. The program concludes with an if __name__ == "__main__": block, which ensures that the main() function is only called if this script is run directly, not if it's imported as a module. This structure allows for a clean, modular design and demonstrates key Python concepts such as user input handling, string manipulation, and conditional logic.

The problem with this code is that you need to wait for the full name to be entered (i.e., concluded by pressing the Enter key) when you actually know the first character after the first character is pressed!

This is where getkey() comes in!

Python getkey module

Python’s getkey is a third-party module that allows you to read individual keystrokes from the user without requiring them to press Enter.

Here is a very basic program using getkey:

from getkey import getkey, keys

key = getkey()
if key == keys.UP:
    print("Up arrow pressed")
elif key == 'a':
    print("A key pressed")

If you run this program, you might get an error like so:

ModuleNotFoundError: No module named 'getkey'

Because getkey is a third party module,, you need to install it first, typically using pip:

pip install getkey

This will give you a message like:

Successfully built getkey
Installing collected packages: getkey
Successfully installed getkey-0.6.5

From this point you are ready to run the above program. What does the program do?

Note that it begins by importing the getkey function and the keys object from the getkey module. It then calls getkey(), which waits for a single keystroke from the user and returns it. The program then uses conditional statements to check the captured key. If the Up arrow key is pressed, which is represented by keys.UP, it prints "Up arrow pressed". Alternatively, if the 'a' key is pressed, it prints "A key pressed". This simple structure showcases how getkey can be used to create interactive programs that respond immediately to specific keystrokes, including special keys like arrow keys, which are not easily captured with standard input methods. The program's brevity belies its power in enabling responsive, keystroke-based user interactions in console applications.

So this program is responsive to only two keys - the up arrow and the “A” key (because that is what you have coded for in the program). If you press any other key it will simply exit - because it will check for both the current conditions, neither of which will be triggered and there are no further statements to be executed.

Name greeter using getkey

Let us rewrite the name greeter program above using getkey instead of input.

from getkey import getkey

print("Start typing your name:")

first_char = getkey()

if first_char.isalpha():
   print(f"Your name starts with '{first_char.upper()}'")
else:
   print("You didn't type a letter.")

As discussed, this program begins by prompting the user to begin typing their name. The program then uses the getkey() function to wait for and capture a single keypress from the user, without requiring them to press Enter. As soon as a key is pressed, the program immediately processes it. It checks whether the captured character is a letter using the isalpha() method. If it is a letter, the program instantly responds by printing a message stating that the user's name starts with that letter, converting it to uppercase for consistency. If the pressed key isn't a letter, the program informs the user of this fact. This approach provides an immediate, responsive interaction, capturing and processing the very first keystroke to give quick feedback about the starting letter of the user's name, all without the need for any additional input or confirmation from the user.

Here are example interactions:

Start typing your name: K
Your name starts with 'K'

Start typing your name: 3
You didn't type a letter.

Animating a stick figure using getkey

Here is a program that displays a stick figure and allows you to animate it, i.e., move it around, by pressing arrow keys like left, right, up and down.

How to use getkey in Python
from getkey import getkey, keys

def draw_stick_figure(x, y):
    figure = [
        "  O  ",
        " /|\\ ",
        " / \\ "
    ]
    
    for i, line in enumerate(figure):
        print(f"\033[{y+i};{x}H{line}")

def clear_screen():
    print("\033[2J\033[H", end="")

def main():
    x, y = 10, 5
    clear_screen()
    draw_stick_figure(x, y)
    
    while True:
        key = getkey()
        
        if key == keys.UP:
            y = max(1, y - 1)
        elif key == keys.DOWN:
            y = min(20, y + 1)
        elif key == keys.LEFT:
            x = max(1, x - 1)
        elif key == keys.RIGHT:
            x = min(70, x + 1)
        elif key == keys.ESC or key == 'q':
            break
        
        clear_screen()
        draw_stick_figure(x, y)

if __name__ == "__main__":
    main()

The program begins by importing the necessary components from the getkey module. This module allows us to capture individual keystrokes from the user without requiring them to press Enter after each key. It's particularly useful for creating interactive console applications like this one.

At the heart of our program is the draw_stick_figure function. This function takes x and y coordinates as parameters and uses ANSI escape codes to position the cursor at those coordinates in the terminal. It then prints a simple ASCII representation of a stick figure using characters like 'O' for the head, '|' for the body, and '/' and '' for the arms and legs. By manipulating these coordinates, we can move the stick figure around the screen.

The clear_screen function is a utility that uses ANSI escape codes to clear the terminal screen and reset the cursor position to the top-left corner. This function is crucial for creating the illusion of movement, as it allows us to redraw the stick figure in a new position without leaving traces of its previous positions.

In the main function, we set up the initial position of our stick figure and enter an infinite loop. This loop is where the magic happens. It continuously waits for a keypress using the getkey() function. Depending on which arrow key is pressed, we update the x or y coordinate of the stick figure, ensuring it stays within the bounds of our imaginary screen (1-70 for x, 1-20 for y).

After each keypress and position update, we clear the screen and redraw the stick figure in its new position. This creates a smooth animation effect as the user moves the figure around. The loop continues until the user presses the 'q' key or the ESC key, at which point the program exits.

This program demonstrates several key concepts in Python programming. It showcases how to create interactive console applications, handle user input in real-time, and use ANSI escape codes for terminal manipulation. It also illustrates the use of functions to organize code, loop structures for continuous program execution, and conditional statements for handling different user inputs.

By combining these elements, we've created a simple yet engaging program that allows users to control a stick figure in a text-based environment. This serves as a great starting point for more complex text-based games or interactive console applications.

Creating a responsive text editor using getpy

Here's another good example application for Python's getkey module that demonstrates how to create a simple text editor with real-time key capture:

from getkey import getkey, keys

def simple_text_editor():
    print("Simple Text Editor (Press ESC to save and exit)")
    text = ""
    cursor_position = 0

    while True:
        print("\033[H\033[J", end="")  # Clear the screen
        print(f"Text: {text[:cursor_position]}|{text[cursor_position:]}")
        print(f"Cursor position: {cursor_position}")

        key = getkey()

        if key == keys.ESC:
            break
        elif key == keys.BACKSPACE:
            if cursor_position > 0:
                text = text[:cursor_position-1] + text[cursor_position:]
                cursor_position -= 1
        elif key == keys.LEFT:
            cursor_position = max(0, cursor_position - 1)
        elif key == keys.RIGHT:
            cursor_position = min(len(text), cursor_position + 1)
        elif key == keys.ENTER:
            text = text[:cursor_position] + "\n" + text[cursor_position:]
            cursor_position += 1
        elif len(key) == 1 and key.isprintable():
            text = text[:cursor_position] + key + text[cursor_position:]
            cursor_position += 1

    print("\nFinal text:")
    print(text)

if __name__ == "__main__":
    simple_text_editor()

Upon starting, the program displays a blank canvas and instructions to press ESC to save and exit. It then enters a continuous loop, waiting for user input. Each keystroke is immediately captured and processed, updating the text and cursor position accordingly. The screen is cleared and redrawn after each keystroke, creating the illusion of a dynamic, responsive interface.

The editor supports a range of functionalities. Users can type any printable character, which is inserted at the current cursor position. The left and right arrow keys move the cursor within the text, allowing for precise positioning. The backspace key deletes the character before the cursor, and the Enter key inserts a new line. All these actions happen instantly, providing immediate visual feedback.

Throughout the editing process, the program displays the current text with a visual cursor indicator (represented by a '|' character) and shows the numerical cursor position. This gives users a clear understanding of where they are in the text and what changes they're making.

When the user presses the ESC key, the editing loop ends. The final version of the text is then displayed, showing the complete result of the user's editing session. This simple yet functional text editor demonstrates the power of the getkey module in creating interactive, responsive console applications that can handle complex input scenarios in real-time.

Here is an example of interaction with the program:

Text: |
Cursor position: 0

Text: K|
Cursor position: 1

Text: Ko|
Cursor position: 2

Text: Kod|
Cursor position: 3

Text: Kodd|
Cursor position: 4

Text: Kod|
Cursor position: 3

..

Note that we made a mistake after “Kod” in typing “Kodeclik” and thus entered the backspace key which was trapped and recognized by our program. Have fun with the above editor and add more bells and whistles to it to satisfy your unique needs!

In summary, the getkey module in Python allows you to read individual keystrokes from the user without requiring them to press Enter. It is not a built-in Python function, but part of a third-party module that needs to be installed separately. The main purpose of getkey() is to capture single keystrokes immediately as they are pressed, without waiting for Enter. It returns a string representation of the key pressed, including special keys like arrow keys, function keys, etc. Most importantly, it provides a cross-platform way to read keystrokes, working on Windows, macOS, and Linux.

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.