Turtle Graphics - 从 onscreenclick 中提取颜色

Turtle Graphics - Extract Color from onscreenclick

我在 Python 中使用 Turtle Graphics 来完成一个更大的程序。我能够 return 用户点击使用 turtle.onscreenclick

的点

但是,我想提取用户点击的点的RGB颜色。这甚至可以在海龟图形中完成吗?如何实现?谢谢!

import turtle

# Global variables specifying the point clicked

xclick = 0
yclick = 0

# Draw a rectangle that is red

height = float(50)
length = height *(1.9)
length = round(length,2)
turtle.begin_fill()
turtle.color("red")
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()

# Gets the click 

def getcoordinates():
    turtle.onscreenclick(turtle.goto)
    turtle.onscreenclick(modifyglobalvariables) 

# Modifies the global variables    

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

getcoordinates()
turtle.done()

turtle 没有获取像素颜色的函数。它使用 tkinter(和小部件 tkinter.Canvas - turtle.getcanvas())来显示所有内容,但它也没有获取像素颜色的功能。

Canvas 将所有对象保留为对象,"Get pixel colors of tkinter canvas" 的第二个答案显示了如何获取位置 (x,y) 中对象的颜色。也许它对你有用。


编辑: 我制作了工作示例

canvas 使用不同的坐标 - 它需要更改 y = -y

import turtle

# --- functions --- (lower_case_names)

def get_pixel_color(x, y):

    # canvas use different coordinates
    y = -y

    canvas = turtle.getcanvas()
    ids = canvas.find_overlapping(x, y, x, y)

    if ids: # if list is not empty
        index = ids[-1]
        color = canvas.itemcget(index, "fill")
        if color != '':
            return color.lower()

    return "white" # default color 

def modify_global_variables(rawx,rawy):
    global xclick
    global yclick

    xclick = int(rawx)
    yclick = int(rawy)

    print(get_pixel_color(xclick, yclick))


def draw_rect(x1, y1, width, height, color):
    y1 = -y1
    canvas = turtle.getcanvas()
    canvas.create_rectangle((x1, y1, x1+width, y1+height), fill=color, width=0)

# --- main ---

# Global variables specifying the point clicked

xclick = 0
yclick = 0

# Draw a rectangle that is red

height = 50.0 # now it is float
length = height * 1.9
length = round(length, 2)

turtle.down()
turtle.color("RED")

turtle.begin_fill()

for _ in range(2):
    turtle.forward(length)
    turtle.right(90) 
    turtle.forward(height)
    turtle.right(90)

turtle.end_fill()

# Use tkinter.Canvas to draw rectangle

draw_rect(100, 100, length, height, 'green')

# Gets the click & Modifies the global variables    

turtle.onscreenclick(modify_global_variables) 

turtle.done()