如何在乌龟中绑定按钮? [英] How to bind a button in turtle?

查看:25
本文介绍了如何在乌龟中绑定按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我已经尝试从 https://docs.python.org/3/找到解决方案 和其他堆栈溢出问题,但我一直找不到.

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()

它只是运行代码 u 所以首先:为什么它不等到我按下向上"?其次,我怎样才能做到这一点?

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?

推荐答案

你需要做onkeylisten调用outsideu 回调函数.

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

像这样:

import turtle

def u():
    t.forward(50)

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

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

turtle.done()

注意在 s.onkey(u, "Up") 我只有 u not u().前者将函数本身传递给 .onkey 以便它知道在 "Up" 键事件发生时调用什么函数.后者只是传递调用 u 的结果(即 None,因为 u 没有 return语句)到 .onkey.

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.

此外,您的代码省略了 turtle.done() 调用.这告诉乌龟进入事件循环,以便它监听事件并响应它们.如果没有它,脚本会打开一个海龟窗口,然后立即关闭它.

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.

顺便说一句,你发布的代码有一个IndentationError;正确的缩进在 Python 中至关重要.

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

这篇关于如何在乌龟中绑定按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆