1

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!

Mikitaka
  • 49
  • 1
  • 6
  • code `(x <= 40 and x <= -40)` can be reduced to `(x <= -40)` - probably you used wrong `<=` and you need `(x <= 40 and x >= -40)` or more readable `(-40 <= x <= 40)` The same problem is with `(y <= 20 and y <= -20)` – furas May 13 '20 at 03:22
  • What do you mean _"doesn't work"_? – acw1668 May 13 '20 at 03:22
  • Maybe first use `print(x)` and `print( x <= 40 and x <= -40 )` to see what you get. – furas May 13 '20 at 03:24
  • @acw1668 I mean that when I click in the area or in any area it won't register the click. – Mikitaka May 13 '20 at 03:26
  • Add `print(x, y)` at the beginning of `click()` and see whether it is shown in the console when you click any area on the turtle screen. – acw1668 May 13 '20 at 03:29
  • Does this answer your question? [How can I create a button in turtle?](https://stackoverflow.com/questions/59902849/how-can-i-create-a-button-in-turtle) – ggorlen Jan 18 '23 at 00:11

1 Answers1

1

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()
cdlane
  • 40,441
  • 5
  • 32
  • 81
  • I had the same idea but for me the button must have text so i set the color of the button to black (the same as the background) but it would end up covering the text. I tried hiding the turtle with `turtle.ht` but then it wouldn't register my click – Mikitaka May 13 '20 at 03:44