Turtle Graphics - Extract Color from onscreenclick

谁都会走 提交于 2019-12-02 09:24:42

turtle doesn't have function to get pixel color. It uses tkinter (and widget tkinter.Canvas - turtle.getcanvas()) to display everything but it doesn't have function to get pixel color too.

Canvas keeps all as objects and second answer for "Get pixel colors of tkinter canvas" shows how to get color of object in position (x,y). Maybe it will work for you.


EDIT: I made working example

canvas uses different coordinates - it needed to change 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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!