如何用 python 乌龟创建按钮

How to create a button with python turtle

所以我想创建一个您可以在 python 中单击的按钮。

我正在用 python 乌龟模块制作一个非常简单的游戏。

这是我的代码 x 是点击的 x 位置,y 是点击的 y 位置。

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)

我希望它在我单击特定区域时执行 运行 一些代码,但是 此代码对我不起作用。

如有任何帮助,我们将不胜感激。

谢谢!

以不同的方式解决问题。不要用乌龟绘制按钮并尝试确定用户是否在 绘图中单击 ,用乌龟制作按钮并在用户单击 时执行某些操作在上:

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

如果您坚持按照自己的方式进行,那么等效代码可能是:

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