python实战系列02-Hex转换为RGB

亓翎_Re-TikaRa Lv4

  是和实战系列01功能相反的存在,练手玩,不确定会不会更新。


代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import tkinter as tk
import re

def hex_to_rgb(hex_color):
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))

def is_valid_input(value):
return bool(re.match("^([0-9a-fA-F]{6})$", value))

def convert():
hex_color = entry_hex.get()

if not is_valid_input(hex_color):
result_label.config(text="输入错误,请输入有效的16进制颜色值")
return

try:
r, g, b = hex_to_rgb(hex_color)
except ValueError:
result_label.config(text="转换错误,请输入有效的16进制颜色值")
return

result_label.config(text="对应的RGB值为:R={}, G={}, B={}".format(r, g, b))

def copy_rgb_code():
root.clipboard_clear()
root.clipboard_append(result_label.cget("text"))

root = tk.Tk()
root.title("16进制转RGB")

label_hex = tk.Label(root, text="16进制颜色值(如:FF00FF,无#):")
label_hex.grid(row=0, column=0)
entry_hex = tk.Entry(root)
entry_hex.grid(row=0, column=1)

convert_button = tk.Button(root, text="转换", command=convert)
convert_button.grid(row=1, column=0, columnspan=2)

copy_button = tk.Button(root, text="复制", command=copy_rgb_code)
copy_button.grid(row=2, column=0, columnspan=2)

result_label = tk.Label(root, text="")
result_label.grid(row=3, column=0, columnspan=2)

root.mainloop()

下载

Github:https://github.com/NIGHT2000/Hex2RGB
QQ群:813686446

  • 标题: python实战系列02-Hex转换为RGB
  • 作者: 亓翎_Re-TikaRa
  • 创建于 : 2024-05-22 23:39:31
  • 更新于 : 2024-11-20 20:35:15
  • 链接: https://re-tikara.fun/posts/57dc070d/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
目录
python实战系列02-Hex转换为RGB