pythonturtle-graphicspython-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?

    while 1:
        turtle.onkey(break, key)

Solution

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