- Pygame 教程
- Pygame - 主页
- Pygame - 概述
- Pygame - 你好世界
- Pygame - 显示模式
- Pygame - 本地模块
- Pygame - 颜色对象
- Pygame - 事件对象
- Pygame - 键盘事件
- Pygame - 鼠标事件
- Pygame - 绘制形状
- Pygame - 加载图像
- Pygame - 在窗口中显示文本
- Pygame - 移动图像
- Pygame - 使用数字键盘移动
- Pygame - 用鼠标移动
- Pygame - 移动矩形对象
- Pygame - 使用文本作为按钮
- Pygame - 转换图像
- Pygame - 声音对象
- Pygame - 混合器通道
- Pygame - 播放音乐
- Pygame - 玩电影
- Pygame - 使用相机模块
- Pygame - 加载光标
- Pygame - 访问 CDROM
- Pygame - 精灵模块
- Pygame - PyOpenGL
- Pygame - 错误和异常
- Pygame 有用资源
- Pygame - 快速指南
- Pygame - 有用的资源
- Pygame - 讨论
Pygame - 使用文本作为按钮
按钮是典型游戏窗口中的重要元素。我们可以使用文本或图像表面对象作为按钮,这样当单击它时就可以触发特定的操作。
让我们尝试显示三个带有文本标题的按钮。
text1=font.render(" START ", True, white) text2=font.render(" PLAY ", True, white) text3=font.render(" STOP ", True, white)
为了在这些按钮周围绘制边框,需要获取它们的 Rect 对象。
rect1 = text1.get_rect(topleft=(10,10)) rect2 = text2.get_rect(topleft= (100,10)) rect3 = text3.get_rect(topleft= (200,10))
在事件循环内,位块复制周围带有红色边框的文本按钮。
screen.blit(text1, rect1) pygame.draw.rect(screen, (255,0,0),rect1,2) screen.blit(text2, rect2) pygame.draw.rect(screen, (255,0,0),rect2,2) pygame.draw.rect(screen, (255,0,0),rect3,2) screen.blit(text3, rect3)
使用 Rect 对象的 collidepoint() 函数来识别哪个按钮被单击。
if event.type == pygame.MOUSEBUTTONDOWN: if rect1.collidepoint(event.pos): msg = "START Button was pressed" if rect2.collidepoint(event.pos): msg = "PLAY Button was pressed" if rect3.collidepoint(event.pos): msg = "STOP Button was pressed"
将适当的消息显示为文本表面 -
img=font.render(msg, True, (0,0,255)) imgrect=img.get_rect() imgrect.center = (200 , 150 ) pygame.draw.rect(screen, bg, imgrect) screen.blit(img, imgrect)
例子
以下是完整的代码 -
import pygame pygame.init() screen = pygame.display.set_mode((400, 300)) done = False font = pygame.font.SysFont("Arial", 14) text1=font.render(" START ", True, white) text2=font.render(" PLAY ", True, white) text3=font.render(" STOP ", True, white) rect1 = text1.get_rect(topleft=(10,10)) rect2 = text2.get_rect(topleft= (100,10)) rect3 = text3.get_rect(topleft= (200,10)) bg = (127,127,127) msg=" " screen = pygame.display.set_mode((400,300)) screen.fill(bg) while not done: for event in pygame.event.get(): screen.blit(text1, rect1) pygame.draw.rect(screen, (255,0,0),rect1,2) screen.blit(text2, rect2) pygame.draw.rect(screen, (255,0,0),rect2,2) pygame.draw.rect(screen, (255,0,0),rect3,2) screen.blit(text3, rect3) if event.type == pygame.QUIT: done = True if event.type == pygame.MOUSEBUTTONDOWN: if rect1.collidepoint(event.pos): msg = "START Button was pressed" if rect2.collidepoint(event.pos): msg = "PLAY Button was pressed" if rect3.collidepoint(event.pos): msg = "STOP Button was pressed" img=font.render(msg, True, (0,0,255)) imgrect=img.get_rect() imgrect.center = (200 , 150 ) pygame.draw.rect(screen, bg, imgrect) screen.blit(img, imgrect) pygame.display.update()
输出
单击每个按钮时,显示窗口显示以下输出 -