So I want to create a button that you can click on in python.
I am making a very simple game with the python turtle module.
here's my code x
is the x position of the click and y
is the y position of the click.
screen = turtle.Screen() #for some context
def click(x, y):
if (x <= 40 and x <= -40) and (y <= 20 and y <= -20):
#code here
screen.onscreenclick(click)
I want it to do the run some code when i click in a specific area but this code doesn't work for me.
any help would be appreciated.
Thanks!
Approach the problem a different way. Don't draw a button with the turtle and try to determine if the user clicked within the drawing, make a button out of a turtle and do something when the user clicks on it:
from turtle import Screen, Turtle
def click(x, y):
button.hideturtle()
button.write("Thank you!", align='center', font=('Arial', 18, 'bold'))
screen = Screen()
button = Turtle()
button.shape('square')
button.shapesize(2, 4)
button.fillcolor('gray')
button.onclick(click)
screen.mainloop()
If you insist on doing it your way, then the equivalent code might be:
from turtle import Screen, Turtle
def click(x, y):
if -40 <= x <= 40 and -20 <= y <= 20:
turtle.write("Thank you!", align='center', font=('Arial', 18, 'bold'))
screen = Screen()
turtle = Turtle()
turtle.hideturtle()
turtle.penup()
turtle.fillcolor('gray')
turtle.goto(-40, -20)
turtle.begin_fill()
for _ in range(2):
turtle.forward(80)
turtle.left(90)
turtle.forward(40)
turtle.left(90)
turtle.end_fill()
turtle.goto(0, 30)
screen.onclick(click)
screen.mainloop()
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.