codingcat3423
codingcat3423

Reputation: 131

Python turtle: check if a key is down

I want to be able to detect if a key is currently down.

I have found the turtle.onkey and turtle.onkeypress functions, however these don't work for me for two reasons:

  1. they are only triggered when the key is pressed or released.
  2. they call a function when you run them.

I want a boolean that is True if the key is held down, or False if the key is not held down.

Upvotes: 1

Views: 3768

Answers (2)

Thierry Lathuille
Thierry Lathuille

Reputation: 24280

You can't get that directly, but you can use a class that will follow the events regarding the keys that you want to be able to check:

import turtle

class WatchedKey:
    def __init__(self, key):
        self.key = key
        self.down = False
        turtle.onkeypress(self.press, key)
        turtle.onkeyrelease(self.release, key)

    def press(self):
        self.down = True

    def release(self):
        self.down = False

# You can now create the watched keys you want to be able to check:
a_key = WatchedKey('a')
b_key = WatchedKey('b')

# and you can check their state by looking at their 'down' attribute
a_currently_pressed = a_key.down

A little demo, the state of 'a' and 'b' will be printed each time you click in the window:

def print_state(x, y):
    print(a_key.down, b_key.down)

screen = turtle.Screen()
screen.onclick(print_state)

turtle.listen()
turtle.mainloop()
turtle.done()

If you want to follow the state of a bunch of keys, you could create their watchers like this:

keys_to_watch = {'a', 'b', 'c', 'd', 'space']

watched_keys = {key: WatchedKey(key) for key in keys_to_watch}

and check individual keys with

b_pressed = watched_keys['b'].down

Upvotes: 3

codingcat3423
codingcat3423

Reputation: 131

I found a solution. I just set it up to change a variable depending on whether the key is down

def wdown():
    global forward
    forward=True
def wup():
    global forward
    forward=False



screen.onkeypress(wdown,"w")
screen.onkey(wup, "w")

Upvotes: 1

Related Questions