龟图形 - 检索重叠形状的颜色

时间:2017-11-27 00:54:13

标签: python turtle-graphics

我有一颗红色的星星部分刻在一个包含橙色圆圈的紫色方块内。我正在提取用户点击的点的颜色。当我点击方块内的圆圈时,返回的颜色是紫色,而不是橙色。当我点击广场内红星的一部分时,程序也会返回紫色。我该如何纠正这个问题?谢谢。

import turtle

def border(height,color):

    height = float(height)
    length = height *(1.9)
    length = round(length,2)

    # Draws a rectangle.
    turtle.begin_fill()
    turtle.color(color)
    turtle.down()
    turtle.forward(length)
    turtle.right(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.forward(length)
    turtle.right(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.end_fill()

def big_shape(vertices, steps, length):
    turtle.color("red")
    turtle.begin_fill()
    for i in range(vertices):
        turtle.forward(length)
        turtle.right(steps*360.0/vertices)
    turtle.end_fill()

def textbox_click(rawx,rawy):
    turtle.up()
    turtle.setposition(rawx,rawy)
    turtle.down()
    rawy = -rawy
    canvas = turtle.getcanvas()
    canvas.pack(fill="both", expand=True)
    ids = canvas.find_overlapping(rawx, rawy, rawx, rawy)
    if ids: # if list is not empty
        index = ids[0]
        color = canvas.itemcget(index, "fill")
        if color != '':
            print(color.lower())

def getcoordinates():
    turtle.onscreenclick(turtle.goto)
    turtle.onscreenclick(modifyglobalvariables) # Here's the change!
    turtle.onscreenclick(textbox_click)

def modifyglobalvariables(rawx,rawy):
    global xclick
    global yclick
    xclick = int(rawx//1)
    yclick = int(rawy//1)
    print(xclick)
    print(yclick)

def main():
    border(150,"purple") 
    turtle.begin_fill()
    turtle.down()
    turtle.color("purple")
    turtle.up()

    # Creates the big shape

    x1=150
    y1=3
    turtle.setposition(x1,y1) 
    big_shape(5,2,50)
    turtle.begin_fill()
    turtle.down()
    turtle.up()

    # Circle
    x1=70
    y1=-107
    turtle.setposition(x1,y1) 
    turtle.begin_fill()
    turtle.circle(50)
    turtle.color("orange")
    turtle.end_fill()

    getcoordinates()

    turtle.done()
main()

1 个答案:

答案 0 :(得分:0)

我看到两个问题

首先:查看previous question中的代码 - 您必须获取最后一个元素ids[-1],而不是第一个ids[0]才能获得最高元素。

第二:你将乌龟移动到点击位置,所以现在turle是最顶层的 - 所以你可以在获得颜色后移动鼠标,然后你仍然可以使用

 index = ids[-1]

或者您必须从最后ids[-2]获得第二名,但是您必须检查ids是否至少包含两个元素

if len(ids) > 1:     # if list has more than only turtle
    index = ids[-2]  # get second from the end