
- Pygame 教程
- Pygame - 主頁
- Pygame - 概述
- Pygame - Hello World
- Pygame - 顯示模式
- Pygame - Locals 模組
- 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()
輸出
當每個按鈕被點選時,顯示視窗將顯示下面的輸出 −



廣告