import pygame
from pygame.locals import *
from sys import exit
def create_scales(height):#用于创建指定大小的图像对象实例,分别表示红,绿,蓝三块区域,主动实例化三个Surface对象
red_scale_surface=pygame.surface.Surface((SCREEN_WIDTH,height))#与窗口Surface等宽,高度自行调整,下同
green_scale_surface=pygame.surface.Surface((SCREEN_WIDTH,height))
blue_scale_surface=pygame.surface.Surface((SCREEN_WIDTH,height))
for x in range(640):
c=int((x/640)*255)#每个x轴部分占RGB颜色的多少,等同x*(255/640)
red=(c,0,0)
green=(0,c,0)
blue=(0,0,c)
line_rect=Rect(x,0,1,height)
pygame.draw.rect(red_scale_surface,red,line_rect)
pygame.draw.rect(green_scale_surface,green,line_rect)
pygame.draw.rect(blue_scale_surface,blue,line_rect)
return red_scale_surface,green_scale_surface,blue_scale_surface
def main():
pygame.init()#初始化pygame以及相关模块
screen=pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT),0,32)#返回一个窗口Surface对象
red_scale, green_scale, blue_scale = create_scales(80)
color=[127,127,127]#初始化为灰色
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
exit()
screen.fill((0,0,0))#使用纯颜色填充窗口Surface对象
screen.blit(red_scale,(0,00))#将红色Surface对象绘制到窗口Surface对象上
screen.blit(green_scale,(0,80))#将绿色Surface对象绘制到窗口Surface对象上
screen.blit(blue_scale,(0,160))#将蓝色Surface对象绘制到窗口Surface对象上
x,y=pygame.mouse.get_pos()#获取鼠标在窗口中的位置
if pygame.mouse.get_pressed()[0]:#获取鼠标按钮状态,get_pressed()[0]为左键是否为按下状态
for component in range(3):
if y > component*80 and y < (component+1)*80:#判断是在哪个Surface对象(red_scale,green_scale,blue_scale)上移动鼠标
color[component] = int((x/639)*255)#操作color列表,component为索引值
pygame.display.set_caption("PyGame Color Test - "+str(tuple(color)))#在窗口标题上显示RGB颜色元组
for component in range(3):
pos = ( int((color[component]/255)*639), component*80+40 )
pygame.draw.circle(screen, (255, 255, 255), pos, 20)#绘制白色圆点.pos圆心坐标,20为圆半径大小
pygame.draw.rect(screen, tuple(color), Rect(0, 240, SCREEN_WIDTH, SCREEN_HEIGHT))#绘制最下面的显示区域,由于上方的if语句不停的改变color列表的数值,死循环中该行语句一直在不停的执行画不同颜色矩形
pygame.display.update()#不断刷新画面
if __name__=="__main__":
#设置非全屏模式下窗口分辨率
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
main()
输出: