python - 返回鼠标Tkinter下图像像素的RGB颜色

标签 python tkinter

我正在尝试从图像中鼠标点击的位置获取 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()

最佳答案

如果您使用的是 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()

引用文献:

Faster method of reading screen pixel in Python than PIL?

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

关于python - 返回鼠标Tkinter下图像像素的RGB颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22647120/

相关文章:

python - 带掩蔽的密集光流

python - 如何使用 Splinter 查找元素值?

python - 处理成功和失败响应 Django

python - 如何在 tkinter 中通过线程打开多个框架?

python - 同时使用复选按钮和按钮

python - 用于多个输入框的弹出数字键盘(数字键盘)

python - 如何确保请求是从轮换 IP 发出的?

python - ttk 比例增加 1

python - 访问类方法内的变量

python - pandas groupby 与 nan 的意思