How to bind a button in turtle?

守給你的承諾、 提交于 2019-12-11 13:11:26

问题


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 simple. While using a code like this:

import turtle
s = turtle.Screen()
def u():
t.forward(50)
s.onkey(u(), "Up")
s.listen()

It simply runs the code u So first of all: Why does it not wait until I press "Up"? And second, how can I make it so that it does?


回答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 u not u(). 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.




回答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:

import turtle
s = 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.



来源:https://stackoverflow.com/questions/35978153/how-to-bind-a-button-in-turtle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!