diligar
diligar

Reputation: 423

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)

Upvotes: 0

Views: 197

Answers (2)

cdlane
cdlane

Reputation: 41905

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!

Upvotes: 1

cdlane
cdlane

Reputation: 41905

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.

Upvotes: 2

Related Questions