# 按钮(未封装) import pygame # 初始化 pygame.init() # 创建窗口 screen_width = 400 # 窗口的宽度 screen_height = 600 # 窗口的高度 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('按钮事件') screen.fill((255, 255, 255)) pygame.display.flip() font = pygame.font.Font("msyhbd.ttc", 20) # 1.确定按钮 bx1, by1, bw1, bh1 = 30, 100, 100, 50 pygame.draw.rect(screen, (255, 0, 0), (bx1, by1, bw1, bh1)) text1 = font.render('确定', True, (0, 0, 0)) tw1, th1 = text1.get_size() tx1 = bx1 + bw1/2 - tw1/2 ty1 = by1 + bh1/2 - th1/2 screen.blit(text1, (tx1, ty1)) # 2.取消按钮 bx2, by2 = 30, 200 pygame.draw. rect(screen, (0, 255, 0), (bx2, by2, bw1, bh1)) text2 = font.render('取消', True, (0, 0, 0)) tw2, th2 = text2.get_size() tx2 = bx2 + bw1/2 - tw2/2 ty2 = by2 + bh1/2 - th2/2 screen.blit(text2, (tx2, ty2)) pygame.display.update() while True: # 检测事件 for event in pygame.event.get(): if event.type == pygame.QUIT: exit() if event.type == pygame.MOUSEBUTTONDOWN: mx, my = event.pos # 是否点击了确定按钮 if bx1 <= mx <= bx1 + bw1 and by1 <= my <= by1 +bh1: # 是否点击了确定按钮 pygame.draw.rect(screen, (200, 200, 200), (bx1, by1, bw1, bh1)) screen.blit(text1, (tx1, ty1)) pygame.display.update() print('确定按钮被点击') # 是否点击了取消按钮 elif bx2 <= mx <= bx2 + bw1 and by2 <= my <= by2 +bh1: pygame.draw.rect(screen, (200, 200, 200), (bx2, by2, bw1, bh1)) screen.blit(text2, (tx2, ty2)) pygame.display.update() print('取消按钮被点击') else: pass if event.type == pygame.MOUSEBUTTONUP: # 确定按钮 pygame.draw.rect(screen, (255, 0, 0), (bx1, by1, bw1, bh1)) screen.blit(text1, (tx1, ty1)) pygame.display.update() # 取消按钮 pygame.draw.rect(screen, (0, 255, 0), (bx2, by2, bw1, bh1)) screen.blit(text2, (tx2, ty2)) pygame.display.update() print('鼠标弹起')
Pygame学习笔记(八)
最新推荐文章于 2024-07-26 17:36:26 发布