Reputation: 367
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
Upvotes: 0
Views: 7041
Reputation: 11473
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()
Upvotes: 0
Reputation: 2347
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
Upvotes: 1