【发布时间】:2021-10-03 13:49:11
【问题描述】:
在这段代码中,我使用 Turtle Module for Python 创建了一个程序,我听说它是用 Tkinter 构建的。这个工作代码会让乌龟说“啊!”当你点击它时,然后传送。最让我困惑的是 t.onclick() 方法。它如何在允许其余代码运行的同时继续监听海龟的点击,这与 input() 函数不同,它在继续之前等待用户输入输入?
另外,事件处理程序在 Python 中是如何工作的?它是否会通过某种永远循环不断检查背景中的点击?是否有一种机制允许它保持空闲并在收到点击时以某种方式激活?还是有其他东西完全可以让它以它的方式工作?
from turtle import *
from time import sleep
from random import randint
t = Turtle()
t.color("red")
t.penup()
t.shape("turtle")
t.speed(100)
t.points = 0
w = 200
h = 150
def rand_move():
t.goto(randint(-w, w), randint(-h, h))
def catch(x, y):
t.write("Ah!", font=("Arial", 14, "normal"))
t.points = t.points + 1
rand_move()
t.onclick(catch)
while t.points < 3:
sleep(1.5)
rand_move()
t.write("WOW! You're good at catching me!", font=('Arial', 16, 'bold'))
t.hideturtle()
我曾尝试查找 Turtle 源代码,但未能破译它,甚至在 Google 上搜索了相当多的网站,但似乎没有一个对这个问题足够具体。任何帮助解决这个问题将不胜感激!
【问题讨论】:
标签: python event-handling python-turtle