Python Turtle - 点击事件

Python Turtle - Click Events

我目前正在 python 的 Turtle Graphics 中制作程序。这是我的代码,以备不时之需

import turtle
turtle.ht()

width = 800
height = 800
turtle.screensize(width, height)

##Definitions
def text(text, size, color, pos1, pos2):
     turtle.penup()
     turtle.goto(pos1, pos2)
     turtle.color(color)
     turtle.begin_fill()
     turtle.write(text, font=('Arial', size, 'normal'))
     turtle.end_fill()

##Screen
turtle.bgcolor('purple')
text('This is an example', 20, 'orange', 100, 100)


turtle.done()

我想要点击事件。因此,在写入文本 'This is an example' 的位置,我希望能够单击该文本并将某些内容打印到控制台或更改背景。我该怎么做?

编辑:

我不想安装 pygame 之类的东西,它必须在 Turtle 中制作

使用 onscreenclick 方法获取位置,然后在主循环中对其进行操作(打印或其他)。

import turtle as t

def main():
    t.onscreenclick(getPos)
    t.mainloop()
main()

另见:Python 3.0 using turtle.onclick 另见:Turtle in python- Trying to get the turtle to move to the mouse click position and print its coordinates

由于您的要求是 onscreenclick 围绕文本区域,我们需要 跟踪鼠标位置。为此,我们将函数 onTextClick 绑定到屏幕事件。 在函数中,如果我们在文本 This is an example 附近,则会调用 turtle.onscreenclick 将背景颜色更改为 red。 您可以更改 lambda 函数并插入您自己的函数,或者根据 this documentation

创建外部函数并在 turtle.onscreenclick 内调用

我尽量少更改您的代码。

这是一个工作代码:

import turtle

turtle.ht()

width = 800
height = 800
turtle.screensize(width, height)

##Definitions
def text(text, size, color, pos1, pos2):
     turtle.penup()
     turtle.goto(pos1, pos2)
     turtle.color(color)
     turtle.begin_fill()
     turtle.write(text, font=('Arial', size, 'normal'))
     turtle.end_fill()


def onTextClick(event):
    x, y = event.x, event.y
    print('x={}, y={}'.format(x, y))    
    if (x >= 600 and x <= 800) and (  y >= 280 and y <= 300):
        turtle.onscreenclick(lambda x, y: turtle.bgcolor('red'))

##Screen
turtle.bgcolor('purple')
text('This is an example', 20, 'orange', 100, 100)

canvas = turtle.getcanvas()
canvas.bind('<Motion>', onTextClick)    

turtle.done()