简体   繁体   English

如何使用乌龟记录按键操作?

[英]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.我没有任何代码,但是如果我使用 onkeypress,似乎我必须创建一个函数来将每个可能的字符附加到用户名变量中,这似乎不是很 Pythonic。 Is there a better way to do this?有一个更好的方法吗?

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.如果我使用onkeypress,似乎我必须创建一个函数来将每个可能的字符附加到用户名变量中,这似乎不是很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.如果你不使用第二个key参数给海龟的onkeypress()函数,它会在按下任何键时调用你的按键处理程序代码。 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 (ie key is None ).我们可以通过重写底层解决此设计错误_onkeypress代码的Tkinter的传递event.char乌龟的事件处理程序,在没有钥匙已设置的情况下(即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 (eg return ) yourself.您需要自己处理特殊字符(例如return )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM