使用pygame实现调色板 ```python
import pygame
from pygame.locals import *
from sys import exit
import numpy as np
pygame.init()
clock = pygame.time.Clock()
FPS = 240
R = 50
BG_color = (109, 171, 228)
SIZE = WIDTH, HEIGHT = 256 * 3 + R * 2 - 1, R * 2 * 3 + 200 + 3
screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption("Pygame设计调色板")
font = pygame.font.SysFont('Microsoft YaHei', 50)
button_1 = False # 添加定义和初始化
blackline_y = [101, 202, 303]
x_initial = [R, R, R] # 储存初始x坐标
x = [R, R, R] # 储存之后每一次变化后的x坐标
delta_x = [0, 0, 0]
x_color = [0, 0, 0] # 计算并储存对应颜色的x值
y = [R, R + 101, R + 202] # 储存每一行的y坐标
dragging = [0, 0, 0] # 储存是否在拖动的状态
def draw_circle():
if dragging == [0, 0, 0]:
in_x = x_initial
else:
in_x = x
for i in range(3):
if 50 <= x[i] <= WIDTH - R:
pygame.draw.circle(screen, pygame.Color('white'), (in_x[i], y[i]), R)
elif x[i] > WIDTH - R:
x[i] = WIDTH - R
elif x[i] < 50:
x[i] = 50
# 画黑色横分割线
def draw_blackline():
with pygame.PixelArray(screen) as pixel:
for i in range(len(blackline_y)):
pixel[:, blackline_y[i]:blackline_y[i]+1] = pygame.Color('black')
# 输入行数,判断距离,返回对错
def distance_height_judge(Row_num):
if (mouse_pos[0] - circle_center[Row_num][0])**2 + \
(mouse_pos[1] - circle_center[Row_num][1])**2 <= R**2 \
and 101*Row_num <= mouse_pos[1] <= 101*Row_num + 100:
return True
else:
return False
# 生成颜色值字符串
def generate_color_value_string(r, g, b):
return f"RGB色值:({r}, {g}, {b})"
while True:
screen.fill(BG_color)
draw_blackline()
draw_circle()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
for i in range(3):
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
if distance_height_judge(i):
dragging[i] = 1
elif event.type == pygame.MOUSEMOTION and dragging[i] == 1:
mouse_pos = pygame.mouse.get_pos()
x_initial[i] = x[i]
delta_x[i] = mouse_pos[0] - x_initial[i]
x[i] += delta_x[i]
button_1 = True
elif event.type == pygame.MOUSEBUTTONUP:
dragging[i] = 0
draw_circle()
if distance_height_judge(i):
button_1 = True
if button_1:
for i in range(3):
x_color[i] = min(max((x[i] - R) // 3, 0), 255)
button_1 = False
# 定义圆心
circle_center_data = [[x[0], 50], [x[1], 151], [x[2], 252]]
circle_center = np.array(circle_center_data)
color_value_str = generate_color_value_string( \
int(x_color[0]), int(x_color[1]), int(x_color[2]))
text = font.render(color_value_str, True, (255, 255, 255))
screen.blit(text, (WIDTH // 2 - text.get_width() / 2, 303 + 60))
# 在文本下方画出颜色
pygame.draw.rect(screen, pygame.color.Color(x_color), \
(0, HEIGHT - 75, WIDTH, 75))
clock.tick(FPS)
pygame.display.update()