获取Tkinter中鼠标下图像像素的RGB颜色

2 投票
2 回答
5920 浏览
提问于 2025-04-17 23:53

我想从我鼠标点击的地方获取图像的RGB值。

我想用Tkinter来完成这个任务,这样代码会简单一些(而且我不知道为什么PIL安装不成功),所以我不确定这样做是否可行。谢谢大家的帮助,我有点困惑。

from serial import *
import Tkinter
class App:
    def __init__(self):
        # Set up the root window
        self.root = Tkinter.Tk()
        self.root.title("Color Select")

        # Useful in organization of the gui, but not used here
        #self.frame = Tkinter.Frame(self.root, width=640, height=256)
        #self.frame.bind("<Button-1>", self.click)
        #self.frame.pack()

        # LABEL allows either text or pictures to be placed
        self.image = Tkinter.PhotoImage(file = "hsv.ppm")
        self.label = Tkinter.Label(self.root, image = self.image)
        self.label.image = self.image #keep a reference see link 1 below

        # Setup a mouse event and BIND to label
        self.label.bind("<Button-1>", self.click)
        self.label.pack()
        # Setup Tkniter's main loop
        self.root.mainloop()

    def click(self, event):
        print("Clicked at: ", event.x, event.y)

if __name__ == "__main__":
    App()

2 个回答

1

我终于决定安装PIL库了。现在我可以成功获取像素数据了,不过我现在在发送串口数据时遇到了一些麻烦...

 def click(self, event):
    im = Image.open("hsv.ppm")
    rgbIm = im.convert("RGB")
    r,g,b = rgbIm.getpixel((event.x, event.y))
    colors = "%d,%d,%d\n" %(int(r),int(g),int(b))
    #print("Clicked at: ", event.x, event.y)
# Establish port and baud rate
    serialPort = "/dev/ttyACM0"
    baudRate = 9600
    ser = Serial(serialPort, baudRate, timeout = 0, writeTimeout = 0)
    ser.write(colors) 
    print colors
2

如果你使用的是Python 2.5或更高版本,可以利用ctypes这个库来调用一个dll函数,这个函数可以返回某个像素的颜色值。通过使用Tkinter的x和y _root方法,你可以获取一个像素的绝对值,然后用GetPixel函数来检查它。这是在Windows 7和Python 2.7上测试过的:

from Tkinter import *
from ctypes import windll

root = Tk()

def click(event):
    dc = windll.user32.GetDC(0)
    rgb = windll.gdi32.GetPixel(dc,event.x_root,event.y_root)
    r = rgb & 0xff
    g = (rgb >> 8) & 0xff
    b = (rgb >> 16) & 0xff
    print r,g,b

for i in ['red', 'green', 'blue', 'black', 'white']:
    Label(root, width=30, background=i).pack()

root.bind('<Button-1>', click)

root.mainloop()

参考资料:

在Python中比PIL更快的读取屏幕像素的方法?

http://www.experts-exchange.com/Programming/Microsoft_Development/Q_22657547.html

撰写回答