Adam Abahot
Adam Abahot

Reputation: 176

How can I log key presses using turtle?

I'm trying to make a simple turtle script that asks the user for their username, and then stores that. I don't have any code, but if I used onkeypress, it seems I would have to make a function for appending every single possible character to the username variable, and that doesn't seem very pythonic. Is there a better way to do this?

Upvotes: 1

Views: 1074

Answers (1)

cdlane
cdlane

Reputation: 41905

if I used onkeypress, it seems I would have to make a function for appending every single possible character to the username variable, and that doesn't seem very pythonic. Is there a better way to do this?

Yes but no. If you leave off the second, key, argument to the turtle's onkeypress() function, it will call your key press handler code when any key is pressed. Problem is, they left off the code to let you know which key!

We can work around this design error by rewriting the underlying _onkeypress code to pass tkinter's event.char to the turtle's event handler in the case where no key has been set (i.e. key is None).

Here's a crude example of this to get you started:

from turtle import Screen, Turtle
from functools import partial

FONT = ('Arial', 18, 'normal')

def _onkeypress(self, fun, key=None):
    if fun is None:
        if key is None:
            self.cv.unbind("<KeyPress>", None)
        else:
            self.cv.unbind("<KeyPress-%s>" % key, None)
    elif key is None:
        def eventfun(event):
            fun(event.char)
        self.cv.bind("<KeyPress>", eventfun)
    else:
        def eventfun(event):
            fun()
        self.cv.bind("<KeyPress-%s>" % key, eventfun)

def letter(character):
    turtle.write(character, move=True, font=FONT)

turtle = Turtle()

screen = Screen()
screen._onkeypress = partial(_onkeypress, screen)
screen.onkeypress(letter)
screen.listen()
screen.mainloop()

Just start typing at the window and your characters will show up. You'll need to handle special characters (e.g. return) yourself.

Upvotes: 4

Related Questions