Skip to content Skip to sidebar Skip to footer

How To Bind A Button In Turtle?

Note: I've already tried to find solutions from https://docs.python.org/3/ and other stack overflow questions, but I haven't been able to find it. What I'm looking for is quite sim

Solution 1:

You need to do the onkey and listen calls outside the u callback function.

Like this:

import turtle

def u():
    t.forward(50)

s = turtle.Screen()
t = turtle.Turtle()

s.onkey(u, "Up")
s.listen()

turtle.done()

Note that in s.onkey(u, "Up") I just have unotu(). The former passes the function itself to .onkey so it knows what function to call when the "Up" key event occurs. The latter just passes the result of calling u (which is None, since u doesn't have a return statement) to .onkey.

Also, your code omits the turtle.done() call. That tells turtle to go into the event loop so it will listen for events and respond to them. Without it, the script opens a turtle window and then closes it immediately.


BTW, the code you posted has an IndentationError; correct indentation is vital in Python.

Solution 2:

You are calling the function when you put parentheses after it. Just take those out to pass the function itself rather than what it returns:

importturtles= turtle.Screen()

def u():
    t.forward(50)

s.onkey(u, "Up")
s.listen()

In Python, functions are objects just like everything else. You don't need parentheses in order to use them. You could do v = u and you would be able to use v(). If you were to say u = 4, you wouldn't be able to use u() any more because now u refers to something else.

Post a Comment for "How To Bind A Button In Turtle?"