Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...