如何使用乌龟记录按键操作? [英] How can I log key presses using turtle?

查看:26
本文介绍了如何使用乌龟记录按键操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的海龟脚本,询问用户的用户名,然后将其存储.我没有任何代码,但是如果我使用 onkeypress,似乎我必须创建一个函数来将每个可能的字符附加到用户名变量中,这似乎不是很 Pythonic.有没有更好的方法来做到这一点?

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?

推荐答案

如果我使用onkeypress,似乎我必须为将每个可能的字符附加到用户名变量,这似乎不是很pythonic.有没有更好的方法来做到这一点?

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?

是但不是.如果您不使用第二个 key 参数给海龟的 onkeypress() 函数,它会在 any 键时调用您的按键处理程序代码被按下.问题是,他们忽略了代码让你知道哪个键!

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!

我们可以通过重写底层的 _onkeypress 代码来解决这个设计错误,以便在没有设置键的情况下将 tkinter 的 event.char 传递给海龟的事件处理程序(即key is None).

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()

只需开始在窗口中输入,您的字符就会显示出来.您需要自己处理特殊字符(例如return).

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

这篇关于如何使用乌龟记录按键操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆