pygame怎么不用按钮组 绘制按钮
时间: 2023-10-29 16:33:47 浏览: 32
你可以使用 Pygame 的 `Rect` 对象来绘制一个矩形,然后计算鼠标点击事件的位置是否在矩形内来实现按钮的功能。以下是一个简单的例子,展示了如何使用矩形绘制一个按钮:
```python
import pygame
# 初始化Pygame
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 定义窗口大小
size = (400, 300)
screen = pygame.display.set_mode(size)
# 设置窗口标题
pygame.display.set_caption("开始页面")
# 加载字体
font = pygame.font.Font(None, 36)
# 创建矩形
button_rect = pygame.Rect(100, 150, 200, 50)
# 游戏循环
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# 检测鼠标点击事件
if event.type == pygame.MOUSEBUTTONDOWN:
# 获取鼠标位置
pos = pygame.mouse.get_pos()
if button_rect.collidepoint(pos):
print("开始游戏")
# 绘制背景颜色
screen.fill(WHITE)
# 绘制矩形
pygame.draw.rect(screen, BLACK, button_rect)
# 绘制文字
font_surface = font.render("开始游戏", True, WHITE)
screen.blit(font_surface, (button_rect.x + button_rect.width / 2 - font_surface.get_width() / 2, button_rect.y + button_rect.height / 2 - font_surface.get_height() / 2))
# 更新屏幕
pygame.display.flip()
# 退出Pygame
pygame.quit()
```
运行代码后,将会弹出一个窗口,窗口上有一个黑色矩形,上面有一个白色的“开始游戏”文字。当点击矩形时,将会在控制台输出“开始游戏”。