Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share

548k questions

547k answers

4 comments

56.5k users

...