How to use Python to make a screen color extractor with Exe file

slandarer 2021-10-29 09:30:58
use python make screen color

0 Use effect

 Insert picture description here
As shown in the moving picture below , Click the color selection button , Move the mouse to the position where you want to pick the color , Wait two seconds to get the color :

 Insert picture description here
Click on save color Buttons can store colors in color library Area , At the same time, as shown in the figure ,

! ! ! ! All the square elements in the red box are actually buttons , Click to get color information ! ! ! !

 Insert picture description here
The information format is :(173, 189, 163) #ADBDA3 (48, 35, 189)

1 what is needed python package

  • PySide2
  • pyautogui
  • pyperclip
  • ctypes
from PySide2.QtWidgets import QApplication,QWidget,QLineEdit
from PySide2.QtWidgets import QLabel,QPushButton
from PySide2.QtGui import QIcon,QFont
from PySide2.QtCore import Qt
import sys
sys.path.append("...")
import time
import pyautogui as pag
import pyperclip
from ctypes import *

2python Tips

2.1 Control array

and matlab equally ,python Controls can also form arrays , For example, when I create a small color box , It's written like this :

# Store color box 
for i in range(0,2):
for j in range(0,10):
storeColorBox=QPushButton(self)
storeColorBox.setGeometry((0.04+0.093*j)*Width,(0.475+0.07*i)*Height,0.08*Width,0.06*Height)
storeColorBox.setStyleSheet(self.SS_Color_Box)
storeColorBox.setProperty("storeId",i*10+j)
storeColorBox.setProperty("Color",'#FFFFFF')
storeColorBox.clicked.connect(self.selectedStore)
self.storeList.append(storeColorBox)

Is to store each color box in self.storeList This array ,
For example, if you want to call number i A color box , That's how it's written :

storeBox=self.storeList[i]

2.2 Use the control as a property

Assign a control as a property to another control
Because we want to get the information in the corresponding text box when we click the label on the left :

 Insert picture description here
That's how it's written ( for instance ):

# Create text box 
self.CB1=QLineEdit(self)
self.CB1.setText("255,255,255")
self.CB1.move(0.62*Width,0.03*Height)
self.CB1.resize(0.35*Width,0.065*Height)
self.CB1.setFont(qf)
self.CB1.setStyleSheet(self.SS_Inf_Box)
# Create a label 
self.CL1=QPushButton(self)
self.CL1.setGeometry(0.448*Width,0.025*Height,0.14*Width,0.075*Height)
self.CL1.setStyleSheet(self.SS_Inf_Label)
self.CL1.setText("RGB")
self.CL1.setFont(qf)
self.CL1.setProperty('Children',self.CB1) # Take the control as a property 
self.CL1.clicked.connect(self.copyInf)# Connected to the callback function 

Then my callback function is written like this :

def copyInf(self):
infLabel=self.sender()
infBox=infLabel.property('Children') # Find the corresponding control by finding the property 
pyperclip.copy(infBox.text())

2.3 How to reset the control color

Or through setStyleSheet Set ow , However, the part of the string that should be put in the color is replaced with the color to be reset :

self.mainBox.setStyleSheet("QPushButton{background:"+self.curColor_HEX
+";border: 3px solid rgb(150,150,150);border-radius:8px}")

2.4 Some string operations used

String letters are capitalized

STR=STR.upper()

String without spaces
For example, put (10, 50, 255) Turn into (10,50,255)

STR=STR.replace(" ", "")

Remove the two parentheses from the string
For example, put (10,50,255) Turn into 10,50,255

STR=STR[1:-1]

2.5 Mouse position pixel color

How to get the pixel color of the current mouse position

import pyautogui as pag
from ctypes import *
x,y=pag.position()
RGB=get_color(x,y)
# obtain x,y Position pixel color 
def get_color(x, y):
gdi32 = windll.gdi32
user32 = windll.user32
hdc = user32.GetDC(None) # Get color value 
pixel = gdi32.GetPixel(hdc, x, y) # extract RGB value 
r = pixel & 0x0000ff
g = (pixel & 0x00ff00) >> 8
b = pixel >> 16
return [r, g, b]

2.6 The window is always at the top

self.setWindowFlags(Qt.WindowStaysOnTopHint)

2.7 The text box cannot be edited, but copying is allowed

use setFocusPolicy(Qt.NoFocus), For example, in the program :

self.CB1.setFocusPolicy(Qt.NoFocus)
self.CB2.setFocusPolicy(Qt.NoFocus)
self.CB3.setFocusPolicy(Qt.NoFocus)

3 Complete code

from PySide2.QtWidgets import QApplication,QWidget,QLineEdit
from PySide2.QtWidgets import QLabel,QPushButton
from PySide2.QtGui import QIcon,QFont
from PySide2.QtCore import Qt
import sys
sys.path.append("...")
import time
import pyautogui as pag
import pyperclip
from ctypes import *
# ===========================================================================================
# Correlation function :
# obtain x,y Position pixel color 
def get_color(x, y):
gdi32 = windll.gdi32
user32 = windll.user32
hdc = user32.GetDC(None) # Get color value 
pixel = gdi32.GetPixel(hdc, x, y) # extract RGB value 
r = pixel & 0x0000ff
g = (pixel & 0x00ff00) >> 8
b = pixel >> 16
return [r, g, b]
# HEX turn RGB
def hex2rgb(hexcolor):
'''HEX turn RGB :param hexcolor: int or str :return: Tuple[int, int, int] >>> hex2rgb(16777215) (255, 255, 255) >>> hex2rgb('0xffffff') (255, 255, 255) '''
hexcolor = int(hexcolor, base=16) if isinstance(hexcolor, str) else hexcolor
rgb = ((hexcolor >> 16) & 0xff, (hexcolor >> 8) & 0xff, hexcolor & 0xff)
return rgb
# RGB turn HEX
def rgb2hex(r, g, b):
color = "#"
color += str(hex(r)).replace('x','0')[-2:]
color += str(hex(g)).replace('x','0')[-2:]
color += str(hex(b)).replace('x','0')[-2:]
return color
# RGB turn HSV
def rgb2hsv(r, g, b):
r, g, b = r/255.0, g/255.0, b/255.0
mx = max(r, g, b)
mn = min(r, g, b)
m = mx-mn
if mx == mn:
h = 0
elif mx == r:
if g >= b:
h = ((g-b)/m)*60
else:
h = ((g-b)/m)*60 + 360
elif mx == g:
h = ((b-r)/m)*60 + 120
elif mx == b:
h = ((r-g)/m)*60 + 240
if mx == 0:
s = 0
else:
s = m/mx
v = mx
H = h / 2
S = s * 255.0
V = v * 255.0
return (round(H), round(S), round(V))
# ===========================================================================================
# Window class :
class Window(QWidget):
def __init__(self,Width=450,Height=600):
super().__init__()
self.setWindowTitle("getScreenColor")
self.setWindowFlags(Qt.WindowStaysOnTopHint)
self.Width=Width
self.Height=Height
# Style sheets 
self.SS_bkg_Label="QLabel{background: rgb(220,220,220);color:rgb(62,62,62);border-radius:8px}"
self.SS_Inf_Label="QPushButton{background: rgb(79,148,204);color:rgb(240,240,240);border-radius:8px}"
self.SS_Inf_Box="QLineEdit{border-radius:3px;border: 2px solid rgb(149,179,215);color:rgb(92,92,92)}"
self.SS_Main_Box="QPushButton{background: #FFFFFF;border: 3px solid rgb(150,150,150);border-radius:8px}"
self.SS_Color_Box="QPushButton{background: #FFFFFF;border: 2px solid rgb(150,150,150);border-radius:3px}"
self.SS_btn_1="QPushButton{background: rgb(214,219,233);color:rgb(82,82,82)}"
self.SS_btn_2="QPushButton{background: rgb(225,235,205);color:rgb(82,82,82)}"
self.SS_btn_3="QPushButton{background: rgb(232,191,190);color:rgb(82,82,82)}"
# Private variables or properties of this class 
self.defaultColor=['#58827E','#144853','#4C6756','#849E77','#ADBDA3',
'#6B1B1E','#A94047','#E05E60','#F8A2AF','#E4CEDB',
'#B0A087','#7F877C','#C7C7BB','#D4C7BE','#E3E4DF',
'#C63866','#FE676E','#FD8F52','#FFBF73','#FFDCA2',
'#7292B8','#769EB8','#B4C5D7','#C5D5EC','#D9E0EA',
'#681F71','#7E0D5D','#6E57A5','#B589BE','#C993B7',
'#3978A4','#81AAAE','#EBCFC4','#FDB8A8','#E3929B','#7D7294']
self.curBoxId=0
self.curColor_RGB=[255,255,255]
self.curColor_HEX='#FFFFFF'
self.curColor_HSV=[0,0,255]
self.storeList=[]
self.defaultList=[]
# The framework constructor calls 
self.setSize()
self.partition()
self.setInfBox()
self.setMainBox()
self.setBtn()
self.setIcon()
self.setColorBox()
# ================================================================================================
# Color box callback function part :
def selectedMain(self):
tColor_HEX=self.curColor_HEX
tColor_RGB=hex2rgb('0x'+tColor_HEX[1:])
tColor_HSV=rgb2hsv(tColor_RGB[0], tColor_RGB[1], tColor_RGB[2])
pyperclip.copy(str(tColor_RGB)+' '+tColor_HEX+' '+str(tColor_HSV))
print(str(tColor_RGB)+' '+tColor_HEX+' '+str(tColor_HSV))
def selectedStore(self):
storeBox=self.sender()
tColor_HEX=storeBox.property("Color")
tColor_RGB=hex2rgb('0x'+tColor_HEX[1:])
tColor_HSV=rgb2hsv(tColor_RGB[0], tColor_RGB[1], tColor_RGB[2])
pyperclip.copy(str(tColor_RGB)+' '+tColor_HEX+' '+str(tColor_HSV))
print(str(tColor_RGB)+' '+tColor_HEX+' '+str(tColor_HSV))
def selectedDefault(self):
defaultBox=self.sender()
tNum=defaultBox.property("defaultId")
tColor_HEX=self.defaultColor[tNum]
tColor_RGB=hex2rgb('0x'+tColor_HEX[1:])
tColor_HSV=rgb2hsv(tColor_RGB[0], tColor_RGB[1], tColor_RGB[2])
pyperclip.copy(str(tColor_RGB)+' '+tColor_HEX+' '+str(tColor_HSV))
print(str(tColor_RGB)+' '+tColor_HEX+' '+str(tColor_HSV))
# ------------------------------------------------------------------------------------------------
# Color information label callback 
def copyInf(self):
infLabel=self.sender()
infBox=infLabel.property('Children')
pyperclip.copy(infBox.text())
print(infBox.text())
# ------------------------------------------------------------------------------------------------
# Button callback function part :
def getColor(self):
time.sleep(2)
x,y=pag.position()
self.curColor_RGB=get_color(x,y)
self.curColor_HSV=rgb2hsv(self.curColor_RGB[0], self.curColor_RGB[1], self.curColor_RGB[2])
self.curColor_HEX=rgb2hex(self.curColor_RGB[0], self.curColor_RGB[1], self.curColor_RGB[2]).upper()
RGB_STR=str(self.curColor_RGB).replace(" ", "")[1:-1]
HSV_STR=str(self.curColor_HSV).replace(" ", "")[1:-1]
self.CB1.setText(RGB_STR)
self.CB2.setText(self.curColor_HEX)
self.CB3.setText(HSV_STR)
self.mainBox.setStyleSheet("QPushButton{background:"+self.curColor_HEX
+";border: 3px solid rgb(150,150,150);border-radius:8px}")
def saveColor(self):
if self.curBoxId<20:
tempBox=self.storeList[self.curBoxId]
tempBox.setProperty("Color",self.curColor_HEX)
tempBox.setStyleSheet("QPushButton{background:"+self.curColor_HEX
+";border: 2px solid rgb(150,150,150);border-radius:3px}")
self.curBoxId+=1
def deleteColor(self):
if self.curBoxId>0:
self.curBoxId-=1
tempBox=self.storeList[self.curBoxId]
tempBox.setProperty("Color",'#FFFFFF')
tempBox.setStyleSheet(self.SS_Color_Box)
# ================================================================================================
# Framework constructor part :
def setSize(self):# Size the frame 
self.setGeometry(80,80,self.Width,self.Height)
self.setMaximumSize(self.Width,self.Height)
self.setMinimumSize(self.Width,self.Height)
def setIcon(self):# Set icon 
appIcon=QIcon("ICON.ico")
self.setWindowIcon(appIcon)
def partition(self):# Each part is divided into 
Width=self.Width
Height=self.Height
qf=QFont()
qf.setBold(True)
qf.setPointSize(12)
qf.setFamily("Cambria")
# --part1-- The current color shows the box background -----
self.bkgLabel1=QLabel(self)
self.bkgLabel1.setGeometry(0.024*Width,0.015*Height,0.4*Width,0.3*Height)
self.bkgLabel1.setStyleSheet(self.SS_bkg_Label)
# --part2-- Current color information background -----
self.bkgLabel2=QLabel(self)
self.bkgLabel2.setGeometry(0.448*Width,0.015*Height,0.528*Width,0.3*Height)
self.bkgLabel2.setStyleSheet("QLabel{background: rgb(235,235,235);border-radius:8px}")
# --part3-- Color repository background -----
self.bkgLabel3=QLabel(self)
self.bkgLabel3.setGeometry(0.024*Width,0.41*Height,0.952*Width,0.205*Height)
self.bkgLabel3.setStyleSheet(self.SS_bkg_Label)
self.bkgLabel3_title=QLabel(self)
self.bkgLabel3_title.setGeometry(0.038*Width,0.415*Height,0.4*Width,0.05*Height)
self.bkgLabel3_title.setStyleSheet(self.SS_bkg_Label)
self.bkgLabel3_title.setText("Color Library")
self.bkgLabel3_title.setFont(qf)
# --part4-- Preset color library background -----
self.bkgLabel4=QLabel(self)
self.bkgLabel4.setGeometry(0.024*Width,0.63*Height,0.952*Width,0.355*Height)
self.bkgLabel4.setStyleSheet(self.SS_bkg_Label)
self.bkgLabel4_title=QLabel(self)
self.bkgLabel4_title.setGeometry(0.038*Width,0.635*Height,0.8*Width,0.05*Height)
self.bkgLabel4_title.setStyleSheet(self.SS_bkg_Label)
self.bkgLabel4_title.setText("Color Library(default)")
self.bkgLabel4_title.setFont(qf)
def setInfBox(self):# Set the information display box 
Width=self.Width
Height=self.Height
# Font settings 
qf=QFont()
qf.setBold(True)
qf.setPointSize(12)
qf.setFamily("Cambria")
# Draw a color information box 
qf.setPointSize(10)
self.CB1=QLineEdit(self)
self.CB1.setText("255,255,255")
self.CB1.move(0.62*Width,0.03*Height)
self.CB1.resize(0.35*Width,0.065*Height)
self.CB1.setFont(qf)
self.CB1.setStyleSheet(self.SS_Inf_Box)
#
self.CB2=QLineEdit(self)
self.CB2.setText("#FFFFFF")
self.CB2.move(0.62*Width,0.13*Height)
self.CB2.resize(0.35*Width,0.065*Height)
self.CB2.setFont(qf)
self.CB2.setStyleSheet(self.SS_Inf_Box)
#
self.CB3=QLineEdit(self)
self.CB3.setText("0,0,255")
self.CB3.move(0.62*Width,0.23*Height)
self.CB3.resize(0.35*Width,0.065*Height)
self.CB3.setFont(qf)
self.CB3.setStyleSheet(self.SS_Inf_Box)
#
self.CB1.setFocusPolicy(Qt.NoFocus)
self.CB2.setFocusPolicy(Qt.NoFocus)
self.CB3.setFocusPolicy(Qt.NoFocus)
# Draw color information labels 
self.CL1=QPushButton(self)
self.CL1.setGeometry(0.448*Width,0.025*Height,0.14*Width,0.075*Height)
self.CL1.setStyleSheet(self.SS_Inf_Label)
self.CL1.setText("RGB")
self.CL1.setFont(qf)
self.CL1.setProperty('Children',self.CB1)
self.CL1.clicked.connect(self.copyInf)
#
self.CL2=QPushButton(self)
self.CL2.setGeometry(0.448*Width,0.125*Height,0.14*Width,0.075*Height)
self.CL2.setStyleSheet(self.SS_Inf_Label)
self.CL2.setText("HEX")
self.CL2.setFont(qf)
self.CL2.setProperty('Children',self.CB2)
self.CL2.clicked.connect(self.copyInf)
#
self.CL3=QPushButton(self)
self.CL3.setGeometry(0.448*Width,0.225*Height,0.14*Width,0.075*Height)
self.CL3.setStyleSheet(self.SS_Inf_Label)
self.CL3.setText("HSV")
self.CL3.setFont(qf)
self.CL3.setProperty('Children',self.CB3)
self.CL3.clicked.connect(self.copyInf)
def setMainBox(self):# Set other label
Width=self.Width
Height=self.Height
# The current color display box in the upper left corner 
self.mainBox=QPushButton(self)
self.mainBox.setGeometry(0.04*Width,0.025*Height,0.368*Width,0.28*Height)
self.mainBox.setStyleSheet(self.SS_Main_Box)
self.mainBox.clicked.connect(self.selectedMain)
def setBtn(self):# Set button 
Width=self.Width
Height=self.Height
# Button font 
qf=QFont()
qf.setBold(True)
qf.setPointSize(10)
qf.setFamily("Cambria")
# Get color button 
self.bnt1=QPushButton(self)
self.bnt1.setGeometry(0.024*Width,0.33*Height,0.4*Width,0.06*Height)
self.bnt1.setStyleSheet(self.SS_btn_1)
self.bnt1.setText("Get Screen Color")
self.bnt1.setFont(qf)
self.bnt1.clicked.connect(self.getColor)
# Save color button 
self.bnt2=QPushButton(self)
self.bnt2.setGeometry(0.444*Width,0.33*Height,0.26*Width,0.06*Height)
self.bnt2.setStyleSheet(self.SS_btn_1)
self.bnt2.setText("Save Color")
self.bnt2.setFont(qf)
self.bnt2.clicked.connect(self.saveColor)
# Delete color button 
self.bnt3=QPushButton(self)
self.bnt3.setGeometry(0.724*Width,0.33*Height,0.26*Width,0.06*Height)
self.bnt3.setStyleSheet(self.SS_btn_3)
self.bnt3.setText("Delete Last")
self.bnt3.setFont(qf)
self.bnt3.clicked.connect(self.deleteColor)
def setColorBox(self):# Draw stored colors and preset color boxes 
Width=self.Width
Height=self.Height
# Store color box 
for i in range(0,2):
for j in range(0,10):
storeColorBox=QPushButton(self)
storeColorBox.setGeometry((0.04+0.093*j)*Width,(0.475+0.07*i)*Height,0.08*Width,0.06*Height)
storeColorBox.setStyleSheet(self.SS_Color_Box)
storeColorBox.setProperty("storeId",i*10+j)
storeColorBox.setProperty("Color",'#FFFFFF')
storeColorBox.clicked.connect(self.selectedStore)
self.storeList.append(storeColorBox)
# Preset color box 
for i in range(0,4):
for j in range(0,10):
if i*10+j<36:
defaultColorBox=QPushButton(self)
defaultColorBox.setGeometry((0.04+0.093*j)*Width,(0.7+0.07*i)*Height,0.08*Width,0.06*Height)
defaultColorBox.setStyleSheet("QPushButton{background: "
+self.defaultColor[i*10+j]+";border: 2px solid rgb(150,150,150);border-radius:3px}")
defaultColorBox.setProperty("defaultId",i*10+j)
defaultColorBox.clicked.connect(self.selectedDefault)
self.defaultList.append(storeColorBox)
# ===========================================================================================
# Function call :
myapp = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(myapp.exec_())

4exe Package

link : https://pan.baidu.com/s/1c2peKrGkg1E92Ata-QRSEg
Extraction code : v85a

版权声明
本文为[slandarer]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/10/20211013205637627q.html

  1. J'ai utilisé Python pour ramper 1000 lettres d'amour pour aider mon colocataire à exprimer les fleurs de classe, mais les inverser et les inverser... C'est le secret ultime des fleurs de classe!
  2. python中列表转为矩阵后无法进行矩阵的乘法运算
  3. Python crawler Development and Learning full tutoriel 2nd Edition, banggan 100000 words [recommended Collection]
  4. Python crawler haut de gamme: microstore confus anti - décryptage
  5. La multiplication de la matrice ne peut pas être effectuée lorsque la liste est convertie en matrice en python
  6. Introduction to operators in python (Part 1)
  7. Are the dictionaries in Python ordered
  8. Introduction to dictionaries in Python
  9. List introduction in Python
  10. pandas比较两个dataframe特定数据列的数值是否相同并给出差值:使用np.where函数
  11. Python使用matplotlib绘制透明背景的可视化图像并保存透明背景的可视化结果(transparent background)
  12. Python self study notes -- basic grammar
  13. Python utilise matplotlib pour dessiner une image visuelle de l'arrière - plan transparent et enregistrer les résultats visuels de l'arrière - plan transparent
  14. Pandas compare les valeurs de deux colonnes de données spécifiques à dataframe et donne des valeurs de voyage: en utilisant la fonction np.where
  15. Comment configurer une application ASGI Django avec Postgres, nginx et uvicorn sur Ubuntu 20.04
  16. What are the advantages of Python and how to get started quickly
  17. Python self study notes -- basic data types
  18. Python code reading (Chapter 14): List Union
  19. Analyse statistique de la fonction de données des essais aléatoires Python
  20. Alien invasion project in Python application -- Aliens (Part 2)
  21. Python code reading (Chapter 14): List Union
  22. Lecture du Code Python (article 25): diviser les chaînes multilignes en listes
  23. Python self study notes -- operators
  24. Formation python - différences entre http et HTTPS
  25. Implementation of automatic timing comment function on Python CSDN platform
  26. python+tkinter+treeview子控件快捷键
  27. Raccourcis clavier pour les sous - contrôles Python + tkinter + treeview
  28. Analyse des données Python
  29. python+tkinter+treeview子控件快捷鍵
  30. Devine si je peux attraper Maotai avec la programmation python? Tout est ouvert à github
  31. À propos de pygame.display.set in Python Un petit problème avec mode ()
  32. Implementation of automatic timing comment function on Python CSDN platform
  33. python:dataframe进行iteritem遍历时如何将输出结果按照列分别输出为该列最后一行
  34. python:dataframe進行iteritem遍曆時如何將輸出結果按照列分別輸出為該列最後一行
  35. Python: comment le dataframe affiche les résultats de sortie par colonne à la dernière ligne de la colonne lors de la traversée de l'itemitem
  36. Écrivez un gadget de bureau pour votre fille préférée en python et elle dit que c'est génial!
  37. Introduction to closures in Python 3
  38. Global / nonlocal usage in Python 3
  39. Introduction to context manager in Python 3
  40. Python crawler selenium framework. You can start with these five questions | Python skill tree
  41. Common standard library random, python introductory tutorial 5 or 6 questions a day | Python skill tree
  42. It is said that Python is omnipotent. It's really good to see Liyang photography circle with Python this time
  43. 【Python 爬虫】 4、爬虫基本原理
  44. 【Python 爬蟲】 4、爬蟲基本原理
  45. 【 Python crawler】 4. Principes de base du crawler
  46. 这道python题到底应该要怎么做
  47. Que doit faire exactement ce problème Python
  48. Après l'importation des variables du module Python, les valeurs imprimées sont fixes.
  49. Nouveau singe Muzi Lee: 0 cours de formation Python de base types de hachage pour les opérations Python redis
  50. Looking at problems from a fresh perspective: analyzing selenium principle from the perspective of Python
  51. Insérez le format de date dans la base de données MySQL en python et ne l'exécutez pas.
  52. Try Python 3.10 with CONDA
  53. Répondez en python et demandez à quelqu'un de vous aider.
  54. Un simple problème de travail Python, qui ne fonctionne pas
  55. Problèmes d'écriture Python pour la boucle
  56. Comment Python exécute les commandes du programme à plusieurs reprises au lieu de quitter
  57. YYDS! Dexplot: one line of Python code to easily draw statistical charts!
  58. pandas生成的透视表如何和源数据一起保存
  59. pandas生成的透視錶如何和源數據一起保存
  60. Comment sauvegarder le tableau pivot généré par pandas avec les données sources