Python TK实现的取色

简介: Python TK实现的取色

一、真相

二、代码

import os
from time import sleep
import tkinter
import tkinter.filedialog
import tkinter.messagebox
from PIL import ImageGrab, Image
root = tkinter.Tk()
root.geometry('100x40+400+300')
root.resizable(False, False)
class MyCapture:
    def __init__(self, png):
        # 变量X和Y用来记录鼠标左键按下的位置
        self.X = tkinter.IntVar(value=0)
        self.Y = tkinter.IntVar(value=0)
        # 获取屏幕尺寸
        screenWidth = root.winfo_screenwidth()
        screenHeight = root.winfo_screenheight()
        # 创建顶级组件容器,与屏幕尺寸一样大
        self.top = tkinter.Toplevel(root, width=screenWidth, height=screenHeight)
        # 不显示最大化、最小化按钮
        self.top.overrideredirect(True)
        self.image = tkinter.PhotoImage(file=png)
        # 创建画布
        self.canvas = tkinter.Canvas(self.top, bg='white', width=screenWidth, height=screenHeight)
        # 显示全屏截图,在全屏截图上进行区域截图
        self.canvas.create_image(screenWidth // 2, screenHeight // 2, image=self.image)
        # 获取鼠标左键抬起的位置,取色
        def onLeftButtonUp(event):
            im = Image.open(png)
            color = im.getpixel((event.x, event.y))[:3]
            color = map(lambda x: hex(x)[2:], color)
            color = map(lambda x: x if len(x) == 2 else '0' + x, color)
            color = '#' + ''.join(color)
            tkinter.messagebox.showinfo('', str(color))
            # 关闭当前窗口
            self.top.destroy()
        self.canvas.bind('<ButtonRelease-1>', onLeftButtonUp)
        self.canvas.pack(fill=tkinter.BOTH, expand=tkinter.YES)
# 开始截图
def buttonCaptureClick():
    # 最小化主窗口
    root.state('icon')
    sleep(0.2)
    filename = 'temp.png'
    im = ImageGrab.grab()
    im.save(filename)
    im.close()
    # 显示全屏幕截图
    w = MyCapture(filename)
    buttonCapture.wait_window(w.top)
    # 截图结束,恢复主窗口,并删除临时的全屏幕截图文件
    root.state('normal')
    os.remove(filename)
buttonCapture = tkinter.Button(root, text='取色', command=buttonCaptureClick)
buttonCapture.place(x=10, y=10, width=80, height=20)
# 启动消息主循环
root.mainloop()

 

 

目录
相关文章
|
2月前
|
Python
Python TK实现的托盘
Python TK实现的托盘
37 0
|
2月前
|
Python
Python TK实现的日历
Python TK实现的日历
36 0
|
2月前
|
调度 Python
Python TK实现的闹钟
Python TK实现的闹钟
23 0
|
2月前
|
关系型数据库 MySQL 数据库
Python tk dos命令备份mysql数据库
Python tk dos命令备份mysql数据库
37 0
|
2月前
|
Python
python tk 显示当前日期和显示阴历
python tk 显示当前日期和显示阴历
31 1
|
2月前
|
人工智能 IDE 开发工具
Python TK输入框Entry设置高度
Python TK输入框Entry设置高度
73 0
|
2月前
|
Python
Python tk 弹出对话框
Python tk 弹出对话框
39 0
|
Python
python: tk demo
# coding=utf-8 import time import tkinter as tk ######################################################################## class Window: def __...
958 0
|
6天前
|
安全 Python
告别低效编程!Python线程与进程并发技术详解,让你的代码飞起来!
【7月更文挑战第9天】Python并发编程提升效率:**理解并发与并行,线程借助`threading`模块处理IO密集型任务,受限于GIL;进程用`multiprocessing`实现并行,绕过GIL限制。示例展示线程和进程创建及同步。选择合适模型,注意线程安全,利用多核,优化性能,实现高效并发编程。
20 3
|
8天前
|
开发者 Python
Python元类实战:打造你的专属编程魔法,让代码随心所欲变化
【7月更文挑战第7天】Python的元类是编程的变形师,用于创建类的“类”,赋予代码在构建时的变形能力。
30 1

相关实验场景

更多