0

I have created a simple Tkinter application with a canvas widget like this:

from tkinter import *
root = Tk()
root.geometry("500x500-500+500")

canvas = Canvas(root, width = 400, height = 400, bg = "white")
canvas.pack()

canvas.create_line(0, 0, 200, 100, width = 20, fill = "black")

root.mainloop()

My question is, how can I get the color of the canvas in a specific position? Say for instance I clicked somewhere on the line, how can I get back the color "black" from that?

In other words, if I wanted a function like this,

def getColor(cnvs, event = None):
   x = event.x
   y = event.y
   # somehow gets the color of cnvs at position (x, y) and stores it as color
   return color

how would I go about doing that?

pineApple
  • 1
  • 3

1 Answers1

1

You can take a screen shot of the canvas using Pillow.ImageGrab module and get the required pixel color from the snapshot image:

from PIL import ImageGrab

def get_color(cnvs, event):
    x, y = cnvs.winfo_rootx()+event.x, cnvs.winfo_rooty()+event.y
    # x, y = cnvs.winfo_pointerx(), cnvs.winfo_pointery()
    image = ImageGrab.grab((x, y, x+1, y+1)) # 1 pixel image
    return image.getpixel((0, 0))

Note that the color returned is in (R, G, B) format.

acw1668
  • 40,144
  • 5
  • 22
  • 34