简体   繁体   中英

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?

    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 . 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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