0

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?

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

1
  • Updated my old post that would change screen color when clicked anywhere to change screen color only specific to text area position as per requirement Commented Apr 13, 2016 at 19:24

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.