【问题标题】:How to create a button with python turtle如何用 python turtle 创建一个按钮
【发布时间】:2020-08-29 02:47:44
【问题描述】:

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

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

这是我的代码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)

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

任何帮助将不胜感激。

谢谢!

【问题讨论】:

  • code (x &lt;= 40 and x &lt;= -40) 可以简化为 (x &lt;= -40) - 可能你使用了错误的&lt;= 并且你需要(x &lt;= 40 and x &gt;= -40) 或更易读的(-40 &lt;= x &lt;= 40) (y &lt;= 20 and y &lt;= -20) 同样的问题
  • 你是什么意思“不起作用”
  • 也许先使用print(x)print( x &lt;= 40 and x &lt;= -40 ) 看看你得到了什么。
  • @acw1668 我的意思是当我点击该区域或任何区域时,它不会注册点击。
  • click()的开头添加print(x, y),看看在海龟屏幕的任意区域点击是否显示在控制台中。

标签: python python-3.x tkinter turtle-graphics tkinter-canvas


【解决方案1】:

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

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

【讨论】:

  • 我有同样的想法,但对我来说按钮必须有文本,所以我将按钮的颜色设置为黑色(与背景相同),但它最终会覆盖文本。我尝试用turtle.ht 隐藏海龟,但它不会注册我的点击
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2017-04-13
  • 1970-01-01
相关资源
最近更新 更多