导读 再简单的游戏界面中均涉及文字处理,下面这篇文章主要给大家介绍了关于python如何在pygame中设置字体并显示中文的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
一、查看可用字体
import pygame
print(pygame.font.get_fonts())
二、设置字体
1.使用系统字体
self.font=pygame.font.SysFont(None,48)#None系统默认字体
self.font = pygame.font.SysFont("arial", 16)
2.使用字体文件

字体文件可以外下载

self.font = pygame.font.Font("my_font.ttf", 16) #字体,字号
3.设置中文()见前2
#系统自带
self.font = pygame.font.SysFont("SimHei", 32)  # 显示中文

在网上下载一个中文字体文件,将这个文件与我们的程序放在同一个文件夹,如果是中文的文件名,将它改成英文文件名。例如,下载了迷你简毡笔黑.TTF,将文件名改成了mnjzbh.ttf,并将程序的第一句改成:

self.font=pygame.font.Font('mnjzbh.ttf',32) # 显示中文
三、附录:常见系统字体对照表

一般的中文字体名,使用拼音即可,如 仿宋fangsong, 楷体kaiti

新细明体:PMingLiU
细明体:MingLiU
标楷体:DFKai-SB
黑体:SimHei
宋体:SimSun
新宋体:NSimSun
仿宋:FangSong
楷体:KaiTi
仿宋_GB2312:FangSong_GB2312
楷体_GB2312:KaiTi_GB2312
微软正黑体:Microsoft JhengHei
微软雅黑体:Microsoft YaHei

一个应用小例子

import pygame.font
 
class BUtton:
    def __init__(self, ai_game, msg):
        """初始化按钮属性"""
        # msg是要在按钮上显示的文本
        self.screen = ai_game.screen
        self.screen_rect = ai_game.screen.get_rect()
 
        # 设置按钮的尺寸和其他属性
        self.width, self.height = 200, 50
        self.buttom_color=(0,255,0)
        self.text_color=(255,255,255)
        self.font=pygame.font.SysFont(None,48)
 
        #创建按钮的rect对象,并使其居中
        self.rect=pygame.Rect(0,0,self.width,self.height)
        self.rect.center=self.screen_rect.center
 
        #按钮的标签只创建一次
        self._pre_msg(msg)
 
    def _pre_msg(self,msg):
        """将msg渲染为图像,并使其在按钮上居中"""
        self.msg_image=self.font.render(msg,True,self.text_color
                                        ,self.buttom_color)
        #布尔实参指定开启还是关闭反锯齿功能,反锯齿让文本的边缘更平滑
        self.msg_image_rect=self.msg_image.get_rect()
        #让图像文本在按钮上居中
        self.msg_image_rect.center=self.rect.center
 
    def draw_button(self):
        """绘制一个用颜色填充的按钮,再绘制文本"""
        self.screen.fill(self.buttom_color,self.rect)
        self.screen.blit(self.msg_image,self.msg_image_rect)
附:在 Pygame 屏幕中添加文字
font = pygame.font.SysFont("freesansbold.ttf", 30)  # 30:font size
text = font.render("content", True, (0,0,0))    # (0,0,0) color of font
self.window.blit(text,(10,10))  # (10,10) rect left top

到此这篇关于python如何在pygame中设置字体并显示中文的文章就介绍到这了

原文来自:https://www.jb51.net/article/273337.htm

本文地址:https://www.linuxprobe.com/python-pygame-linux.html编辑:倪家兴,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/