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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…