简体   繁体   中英

Python Turtle - Click Events

I'm currently making a program in python's Turtle Graphics. Here is my code in case you need it

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

I want to have click events. So, where the text 'This is an example' is wrote, I want to be able to click that and it prints something to the console or changes the background. How do I do this?

EDIT:

I don't want to install anything like pygame, it has to be made in Turtle

Use the onscreenclick method to get the position then act on it in your mainloop (to print or whatever).

import turtle as t

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

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

Since your requirement is to have onscreenclick around text area, we need to track mouse position. For that we are binding function onTextClick to the screenevent. Within function, if we are anywere around text This is an example , a call is made to turtle.onscreenclick to change color of the background to red . You can change lambda function and insert your own, or just create external function and call within turtle.onscreenclick as per this documentation

I tried to change your code as little as possible.

Here is a working Code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM