You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何准确获取Turtle画布指定坐标的填充颜色?

问题:如何正确获取Turtle画布指定坐标的填充颜色?

我希望创建一个函数,返回Turtle画布上指定坐标位置的填充颜色。我使用了turtle库的find_overlapping方法查找画布上的对象,但该方法无法始终返回预期结果。

当前实现方法:

from turtle import *

def get_pixel_color(x, y):
    y = -y
    canvas = getcanvas()
    ids = canvas.find_overlapping(x, y, x, y)
    if ids:
        index = ids[-1]
        color = canvas.itemcget(index, "fill")
        if color:
            return color
    return "white"

即使画布上指定坐标存在填充颜色,该方法有时仍会返回"white"。示例代码如下:

from turtle import *

def get_pixel_color(x, y):
    y = -y
    canvas = getcanvas()
    ids = canvas.find_overlapping(x, y, x, y)
    print(ids)
    if ids:
        index = ids[-1]
        color = canvas.itemcget(index, "fill")
        print(canvas.itemcget(index, "fill"))
        if color:
            return color
    return "white"

def frange(start, stop, step):
    while start <= stop:
        yield start
        start += step
        
SIZE = 40
tracer(0)
screensize(14000, 14000)
color('red')
position = pos()
left(90)
color('yellow')
begin_fill() 

for i in range(5):
    fd(9 * SIZE)
    rt(120)

end_fill()

color('red')
up()
setpos(position)
rt(120)
down()
for i in range(5):
    fd(9 * SIZE)
    rt(120)

up()
update()
c = 0

for x in range(-5, 10):
    for y in range(-5, 13):
        real_x, real_y = x * SIZE, y * SIZE
        print(get_pixel_color(real_x, real_y), pencolor())
        if get_pixel_color(real_x, real_y) == 'yellow':
            setpos(real_x, real_y)
            dot(5, 'blue')
            continue
            

done()

解决方案

问题原因

find_overlapping会返回所有包含指定点的图形ID,包括线条和填充图形。在你的示例中,红色线条绘制在黄色填充图形的上方,ids[-1]会选中顶层的红色线条——而线条的fill属性为空,因此函数返回默认的"white",忽略了下方的黄色填充。

修改后的函数

遍历所有重叠的图形ID,从顶层到底层(逆序遍历ids),找到第一个具有非空填充颜色的对象:

from turtle import *

def get_pixel_color(x, y):
    y = -y  # 转换Turtle坐标到tkinter canvas坐标
    canvas = getcanvas()
    ids = canvas.find_overlapping(x, y, x, y)
    
    # 从顶层到底层遍历,优先获取上层有填充的颜色
    for idx in reversed(ids):
        fill_color = canvas.itemcget(idx, "fill")
        if fill_color:
            return fill_color
    return "white"

说明

  • 逆序遍历ids是因为tkinter canvas中后绘制的图形在顶层,find_overlapping返回的ID顺序是从底层到顶层,逆序后先检查顶层对象。
  • 跳过所有无填充颜色的对象(比如线条),直到找到第一个有填充颜色的图形,确保返回的是指定点实际显示的填充颜色。

将示例代码中的get_pixel_color替换为上述版本后,即可正确识别黄色填充区域,在对应位置绘制蓝色圆点。

内容的提问来源于stack exchange,提问作者sirniki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 11:30:18