SoFunction
Updated on 2024-11-19

How to set fonts in python and display Chinese in pygame Details

I. View available fonts

import pygame
print(.get_fonts())

Second, set the font

1. Use system fonts

=(None,48)#None system default font
 = ("arial", 16)

2. Using font files

Font files can be downloaded externally

 = ("my_font.ttf", 16) #Font, font size

3. Setting Chinese () See previous 2

#System comes with
 = ("SimHei", 32)  # Display Chinese

Download a Chinese font file on the Internet, put this file in the same folder with our program, and if the file name is in Chinese, change it to an English file name. For example, download Mini Simple Felt Pen Black.TTF, change the file name and change the first sentence of the program to:

=('',32) # Display Chinese

III. Appendix: Comparison table of common system fonts

For general Chinese font names, just use pinyin, e.g., fangsong, kaiti.

Newly Refined: PMingLiU
Mincho: MingLiU
Italics: DFKai-SB
Bold: SimHei
Song: SimSun
New Song Style: NSimSun
FangSong
Italics: KaiTi
FangSong_GB2312: FangSong_GB2312
KaiTi_GB2312: KaiTi_GB2312
Microsoft JhengHei: Microsoft JhengHei
Microsoft YaHei: Microsoft YaHei

A small example of an application

import 

class BUtton:
    def __init__(self, ai_game, msg):
        """Initialize button properties"""
        # msg is the text to be displayed on the button
         = ai_game.screen
        self.screen_rect = ai_game.screen.get_rect()

        # Set the size and other properties of the button
        ,  = 200, 50
        self.buttom_color=(0,255,0)
        self.text_color=(255,255,255)
        =(None,48)

        # Create the rect object of the button and center it
        =(0,0,,)
        =self.screen_rect.center

        Labels for #buttons are created only once
        self._pre_msg(msg)

    def _pre_msg(self,msg):
        """Render the msg as an image and center it on the button"""
        self.msg_image=(msg,True,self.text_color
                                        ,self.buttom_color)
        #Boolean parameter specifying whether to turn on or off the anti-aliasing feature, which smoothes the edges of text.
        self.msg_image_rect=self.msg_image.get_rect()
        #Center image text on buttons
        self.msg_image_rect.center=

    def draw_button(self):
        """Draw a button with a color fill and then draw the text"""
        (self.buttom_color,)
        (self.msg_image,self.msg_image_rect)

P.S. Adding text to the Pygame screen

font = ("", 30)	# 30:font size
text = ("content", True, (0,0,0))	# (0,0,0) color of font
(text,(10,10))	# (10,10) rect left top

summarize

to this article on python how to set up fonts in pygame and display the Chinese article is introduced to this, more related pygame set up fonts and display the Chinese content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!