[Python] 纯文本查看 复制代码
from ctypes import windll
import cv2
from numpy import array as arr
from win32api import GetCursorPos, SetCursorPos
import wx
from PIL import ImageGrab
class colorData:
def __init__(self, pos=None, color=None, rgb=None):
self.pos = pos
self.color = color
self.rgb = rgb
class ColorFrame(wx.Dialog):
def __init__(self):
windll.user32.SetProcessDPIAware()
super().__init__(None, title='Desktop Color', size=(200, 300))
self.panel = wx.Panel(self)
self.zb = wx.StaticText(self.panel, label='坐标:(0, 0, 0)', style=wx.ALIGN_CENTER)
self.ys = wx.StaticText(self.panel, label='颜色:(0, 0, 0)', style=wx.ALIGN_CENTER)
self.RGB = wx.StaticText(self.panel, label='RGB:(0, 0, 0)', style=wx.ALIGN_CENTER)
self.bitmap = wx.StaticBitmap(self.panel, size=(200, 200))
self.data = colorData()
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.zb, proportion=1, flag=wx.EXPAND)
sizer.Add(self.ys, proportion=1, flag=wx.EXPAND)
sizer.Add(self.RGB, proportion=1, flag=wx.EXPAND)
sizer.Add(self.bitmap, proportion=1, flag=wx.EXPAND | wx.ALL)
self.panel.SetSizer(sizer)
self.Bind(wx.EVT_CLOSE, self.on_close)
self.Bind(wx.EVT_CHAR_HOOK, self.on_key_press)
# 创建一个定时器来定期获取桌面颜色并更新标签
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.on_timer, self.timer)
self.timer.Start(1) # 每隔1秒触发一次定时器
def on_timer(self, event):
point = GetCursorPos()
screenshot = ImageGrab.grab()
color = screenshot.getpixel(point)
img = arr(ImageGrab.grab((point[0] - 10, point[1] - 10, point[0] + 10, point[1] + 10)))
img = cv2.resize(img, None, None, fx=10, fy=10, interpolation=cv2.INTER_AREA)
cv2.rectangle(img, (100, 100), (110, 110), (255, 0, 0), 1)
self.update_label(point, color, img)
def update_label(self, point, color, img):
self.zb.SetLabel(f'坐标:({point[0]}, {point[1]})')
self.ys.SetLabel(f'颜色:({color[0]}, {color[1]}, {color[2]})')
self.RGB.SetLabel(f'RGB:({color[0]:02X}{color[1]:02X}{color[2]:02X})')
height, width, _ = img.shape
self.maps = wx.Bitmap.FromBuffer(width, height, img) # 将Opencv图像转换为wxPython图像对象
self.bitmap.SetBitmap(self.maps)
def on_close(self, event):
self.timer.Stop()
self.Destroy()
def on_key_press(self, event):
keycode = event.GetKeyCode()
point = GetCursorPos()
if keycode == wx.WXK_RETURN or keycode == wx.WXK_NUMPAD_ENTER:
screenshot = ImageGrab.grab()
color = screenshot.getpixel(point)
self.data.pos = point
self.data.color = color
self.data.rgb = f'{color[0]:02X}{color[1]:02X}{color[2]:02X}'
self.on_close(event)
# self.EndModal(wx.ID_OK)
elif keycode == wx.WXK_LEFT:
SetCursorPos((point[0] - 1, point[1]))
elif keycode == wx.WXK_RIGHT:
SetCursorPos((point[0] + 1, point[1]))
elif keycode == wx.WXK_UP:
SetCursorPos((point[0], point[1] - 1))
elif keycode == wx.WXK_DOWN:
SetCursorPos((point[0], point[1] + 1))
def get_data(self):
return self.data
app = wx.App()
frame = ColorFrame()
frame.Show()
app.MainLoop()
print(frame.data.pos, frame.data.color, frame.data.rgb)