简体   繁体   English

接受Turtle中的按键更简单的方法?

[英]Easier Way to Accept Key Presses in Turtle?

Instead of having to do something long and ugly like this: 不必像这样长而丑陋地做一些事情:

    def change_variable():
        global variable
        variable+=1

    def function(var, key):
        global variable
        variable=var
        turtle.listen()
        turtle.onkey(change_variable, key)

Is there a way to do the following? 有没有办法做到以下几点? Any modules or maybe an update I need? 我需要任何模块或更新吗?

    turtle.onkey(variable+=1, key)

And, in addition, being able to do the following would make things 1000x easier for me, is this possible? 而且,能够执行以下操作会使我的工作变得简单1000倍,这可能吗?

    while 1:
        turtle.onkey(break, key)

You could use a closure and consolidate the ugliness into a smaller area: 您可以使用闭包并将丑陋合并到一个较小的区域:

def function(var, key):
    def change_variable():
        nonlocal var
        var += 1
        print(var)  # just to prove it's incrementing
    turtle.listen()
    turtle.onkey(change_variable, key)

I'm assuming the global variable was part of the ugliness, if not and you need it, then just add it back and change nonlocal to global . 我假设全局variable是丑陋的一部分,如果不是,并且您需要它,则只需将其重新添加,然后将nonlocal更改为global That would reduce the closure to just an inner function. 这样可以将闭包简化为内部函数。

The solution to this: 解决方案:

while 1:
        turtle.onkey(break, key)

is somewhat similar: 有点类似:

def outer(key):
    keep_going = True

    def quit_loop():
        nonlocal keep_going
        keep_going = False

    turtle.onkey(quit_loop, key)
    turtle.listen()
    while keep_going:
        turtle.left(70)
        turtle.forward(200)
    print("Done!")

Though probably not the short, easy solution you were hoping for! 尽管可能不是您所希望的短而简单的解决方案!

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

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