2014-03-25 101 views
2

我試圖讓從圖像在以往任何時候我的鼠標點擊的RGB值回到RGB顏色鼠標的Tkinter

我試圖做這一切只用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() 
+0

不要認爲沒有PIL是可能的。 – alecxe

+0

您使用的是什麼版本的Python? – atlasologist

回答

1

如果你正在使用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

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 
+0

FYI Tkinter PhotoImage有一個get方法來「返回X,Y像素的顏色(紅色,綠色,藍色) – Oblivion