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

问题描述

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

>>> data={
...       "type": "open",...       "initiatorId": "ecc52cc1-a3e4-4037-a80f-62d3799645f4",...       "dateCreated": datetime.datetime.Now().strftime("%Y-%m-%d %H:%M:%s"),...       "subjectId": "8a921487-859f-4931-8743-f69c38f91b25",...       "additionalInfo": {
...         "someInfo": {
...           "abcd":"123",...           "efgh":"456"
...         }
...       }
...     }
>>> response = requests.post(
...     url='https://httpbin.org/post',...     headers={'Authorization': 'abc'},...     json=data)
>>> print(response.text)
{
  "args": {},"data": "{\"type\": \"open\",\"initiatorId\": \"ecc52cc1-a3e4-4037-a80f-62d3799645f4\",\"dateCreated\": \"2021-04-22 09:57:44\",\"subjectId\": \"8a921487-859f-4931-8743-f69c38f91b25\",\"additionalInfo\": {\"someInfo\": {\"abcd\": \"123\",\"efgh\": \"456\"}}}","files": {},"form": {},"headers": {
    "Accept": "*/*","Accept-Encoding": "gzip,deflate","Authorization": "abc","Content-Length": "226","Content-Type": "application/json","Host": "httpbin.org","User-Agent": "python-requests/2.25.1","X-Amzn-Trace-Id": "Root=1-60812c84-58af3b816a5d3fc26cf5f37f"
  },"json": {
    "additionalInfo": {
      "someInfo": {
        "abcd": "123","efgh": "456"
      }
    },"dateCreated": "2021-04-22 09:57:44","initiatorId": "ecc52cc1-a3e4-4037-a80f-62d3799645f4","subjectId": "8a921487-859f-4931-8743-f69c38f91b25","type": "open"
  },"origin": "62.216.206.48","url": "https://httpbin.org/post"
}

你会如何在主函数调用这个函数

解决方法

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

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

from turtle import Screen,Turtle

而不是 import turtlefrom turtle import *。它为海龟引入了面向对象的 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 任何内容,因为它们的调用者无法对返回值执行任何操作。您的事件处理必须某事,而不是返回任何事。