Python - 在 PyGame 視窗中顯示文字


Pygame 是一個針對 Python 的多媒體庫,用於製作遊戲和多媒體應用。在本文中,我們將介紹如何使用 pygame 模組在螢幕上獲取自定義字型和文字,同時考慮到其高度、寬度和在 pygame 視窗中的位置。

在下面的程式中,我們初始化 pygame 模組,然後為影像定義模式和標題。接下來,我們新增字型文字並定義字型座標。screen.blit 函式繪製螢幕,而 while 迴圈不斷監聽遊戲結束是否已單擊。

示例

import pygame
import sys
# Initialize pygame
pygame.init()
#scren dimension
sur_obj=pygame.display.set_mode((300,200))
# Screen caption
pygame.display.set_caption("Text in Pygame")
font_color=(0,150,250)
font_obj=pygame.font.Font("C:\Windows\Fonts\segoeprb.ttf",25)
# Render the objects
text_obj=font_obj.render("Welcome to Pygame",True,font_color)
while True:
   sur_obj.fill((255,255,255))
   sur_obj.blit(text_obj,(22,0))
   for eve in pygame.event.get():
      if eve.type==pygame.QUIT:
         pygame.quit()
         sys.exit()
   pygame.display.update()

輸出

執行以上程式碼,我們得到以下結果:

更新日期: 2021-01-25

740 次瀏覽

開啟你的 事業

透過完成課程獲得認證

開始
廣告