tkinter模拟调色盘

Posted by ZMY on September 7, 2020

使用tkinter模拟调色盘

背景

最近在使用tkinter模拟一些小工具,因为最近工作中会使用web在线调色盘,故想使用tkinter模拟一个本地的调色盘,方便使用

目的

使用tkinter模拟调色盘,供本地使用

环境

python3.7+win7

程序设计思路

1.主框架使用scale结合entry展示,entry中可直接输入16进制颜色值呈现颜色 2.按调色盘按钮调用调色盘,可使用调色盘选取自己喜欢的颜色 3.按OK键调色盘选取颜色呈现在主框架中

程序说明

# -*- coding:utf-8 -*-
from tkinter import *
from tkinter import messagebox
from tkinter.colorchooser import *
root = Tk()
root.geometry("360x360+150+150")
root.update()
x = root.winfo_x()
y = root.winfo_y()
var = StringVar()
#用toplevel调整调色盘
t1 = Toplevel()
t1.geometry("+%d+%d" %(x+250,y+100))
#隐藏toplevel
t1.withdraw()
#显示调色盘
def display_palette():
    (rgb,hx)=askcolor(parent=t1)
    root.config(bg=hx)
    var.set(hx)
    h1=hx[1:3]
    h2=hx[3:5]
    h3=hx[5:7]
    s1.set(int(h1,16))
    s2.set(int(h2,16))
    s3.set(int(h3,16))
#通过尺度条刻度值调整颜色
def updatecolor_scale(args):
    red = s1.get()
    green = s2.get()
    blue = s3.get()
    mycolor="#%02x%02x%02x"%(red,green,blue)
    root.config(bg=mycolor)
    var.set(mycolor)
#通过输入值调整颜色
def updatecolor_entry(args):
    hexcolor = var.get()
    if not hexcolor.startswith('#',0,1):
        messagebox.showwarning(message='请以#开始')
    if len(hexcolor) != 7:
        messagebox.showwarning(message='输入数值在"#000000-#FFFFFF"之间')
    try:
        h1=hexcolor[1:3]
        h2=hexcolor[3:5]
        h3=hexcolor[5:7]
        s1.set(int(h1,16))
        s2.set(int(h2,16))
        s3.set(int(h3,16))
        root.config(bg=hexcolor)
    except:
        root.config(bg='#FFFFFF')
        s1.set(255)
        s2.set(255)
        s3.set(255)
#设计尺度条定位初始数值
s1 = Scale(root,from_=0,to=255,length=230,command=updatecolor_scale,orient='horizontal')
s2 = Scale(root,from_=0,to=255,length=230,command=updatecolor_scale,orient='horizontal')
s3 = Scale(root,from_=0,to=255,length=230,command=updatecolor_scale,orient='horizontal')
s1.set(255)
s2.set(255)
s3.set(255)
#通过尺度条数值转换成16进制颜色表示
hexs1=hex(s1.get()).lstrip('0x')
hexs2=hex(s2.get()).lstrip('0x')
hexs3=hex(s3.get()).lstrip('0x')
var.set('#'+hexs1+hexs2+hexs3)
l=Label(root,text='color(16)请输入:')
e=Entry(root,width=20,textvariable=var)
e.bind('<Return>',updatecolor_entry)
b=Button(root,text='显示调色盘',command=display_palette)
#各主键定位
s1.grid(row=0,columnspan=2,sticky='w')
s2.grid(row=1,columnspan=2,sticky='w')
s3.grid(row=2,columnspan=2,sticky='w')
l.grid(row=3,column=0,sticky='w')
e.grid(row=3,column=1,sticky='w')
b.grid(row=4,sticky='w')
root.mainloop()

其中Toplevel是为了将调色盘显示位置不跟主框架重叠而设计,人后使用withdraw方法进行隐藏

动态演示

声明:本博客的原创文章,都是本人平时学习所做的笔记,转载请标注出处,谢谢合作。