turtle.onclick 和 turtle.onscreenckick() 之间的区别

Difference between turtle.onclick and turtle.onscreenckick()

这两个乌龟事件有什么区别?你能给出 x 和 y 坐标中包含的 turtle.onscreenclick 参数吗?例如 turtle.onscreenclick(x,y, some_variable) 我希望它在单击乌龟图形 window 上的特定坐标范围时启动另一个功能。见下文:

def click_event(x, y):
    if turtle.xcor() >= 0 and turtle.xcor() <= 100 and turtle.ycor() >= 0 and turtle.ycor() <= 100:
        print('Click position at ', x,y)
        calcSum(num1, num2)
    else:
        print('You are out of range')

def calcSum(number1, number2):
    my_sum = number1 + number2
    return my_sum

def main():
    # Call the functions in the main function

如何在主函数中调用这个函数?

有两种onclick()方法,一种用于设置单击乌龟时执行的函数,另一种用于设置单击屏幕任意位置时执行的函数。如果你点击海龟,点击屏幕上任何地方的事件处理函数也会被触发,如果两者都被启用,先是海龟,然后是屏幕。

turtle 模块的双重 功能性面向对象 特性在这个问题上可能会造成混淆。默认的 turtle 的 onclick() 方法是全局 onclick() 函数。单一屏幕实例的 onclick() 方法是全局 onscreenclick() 函数。这是我推荐导入的原因之一:

from turtle import Screen, Turtle

而不是 import turtlefrom turtle import *。它为 turtle 引入了面向对象的 API,并屏蔽了功能性的 API,以避免混淆。粗略地说,您的代码片段将是:

from turtle import Screen, Turtle

def click_event(x, y):
    if 0 <= x <= 100 and 0 <= y <= 100:
        print('Clicked position at:', (x, y))
        calcSum(x, y)
    else:
        print('You are out of range')

def calcSum(number1, number2):
    my_sum = number1 + number2

    turtle.clear()
    turtle.write(my_sum)

turtle = Turtle()

screen = Screen()
screen.onclick(click_event)
screen.mainloop()

如果您只单击原点的左侧和上方,屏幕上会显示一个总和。请注意,您定义的事件处理程序不会 return 任何内容,因为它们的调用者无法对 return 值执行任何操作。你的事件处理必须一些事情,而不是return任何事情。