Pygame学习笔记(八)

# 按钮(未封装)
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('鼠标弹起')
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值