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()

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亚丁号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值