Table of Contents
Pygame’s Font text and font
my_font = pygame.font.Font(filename, size)
Copy after login
" >When we want to introduce a cooler font into the game but it does not exist in the system, we can An alternative method is to load font files externally to draw text. The syntax format is as follows:
my_font = pygame.font.Font(filename, size)
Copy after login
Home Backend Development Python Tutorial Python's Pygame Font module - how to use text and fonts?

Python's Pygame Font module - how to use text and fonts?

Apr 23, 2023 pm 11:19 PM
python pygame font

Pygame’s Font text and font

Pygame creates a font object through the pygame.font module to achieve the purpose of drawing text.
The common methods of this module are as follows:

Cancel initialization of the font module##pygame.font.get_init() pygame.font.get_default_font() pygame.font.get_fonts() pygame.font.match_font() pygame.font.SysFont() pygame.font.Font()
Name Description
pygame.font.init() Initialize the font module
##pygame.font.quit()
Check whether the font module has been initialized and return a Boolean value.
Get the file name of the default font. Return the file name of the font in the system
Get all available fonts, the return value is all available Font list
Matches font files from the system’s font library, and the return value is the complete font File path
Create a Font object from the system’s font library
Create a Font object from a font file
The Font

module provides two methods for creating font (Font) objects, namely:

  • SysFont

    (Load font files from the system to create font objects )

  • Font

    (Create font object through file path)

font.SysFont()

Use the following method to load fonts directly from the system:

pygame.font.SysFont(name, size, bold=False, italic=False)
Copy after login

Parameter description is as follows:

    ##name
  • : List parameter Value, indicating the name of the font to be loaded from the system. It will be searched in the order of the elements in the list. If there is no font in the list in the system, Pygame's default font will be used.

  • size
  • : Indicates the size of the font;

  • bold
  • : Whether the font is bold;

  • italic
  • : Whether the font is italic.

    Usage examples are as follows:
  • print("获取系统中所有可用字体",pygame.font.get_fonts())
    my_font = pygame.font.SysFont(['方正粗黑宋简体','microsoftsansserif'],50)
    Copy after login

The above method will give priority to "Founder Bold Black Song Simplified".

font.Font()

When we want to introduce a cooler font into the game but it does not exist in the system, we can An alternative method is to load font files externally to draw text. The syntax format is as follows:
my_font = pygame.font.Font(filename, size)
Copy after login

The parameter description is as follows:

    filename
  • : string format, indicating the path of the font file;

  • size
  • : Set the font size.

    Usage example is as follows:
  • f = pygame.font.Font('C:/Users/Administrator/Desktop/willhar_.ttf',50)
    Copy after login
Loaded a font file from the desktop to create a font object and set the font size to 50. Note that the above font files are downloaded from the Internet, you can also download them by clicking on the URL), or use the font files in the system library.

Font object methods

Pygame provides some common methods for handling font objects, as follows:

NameDescription##pygame.font.Font.render() pygame.font.Font.size() Whether to draw an underline for the text contentCheck whether the text is underlinedStart bold font rendering##pygame.font.Font.get_bold() Check whether the text is rendered in boldpygame.font.Font.set_italic() Start italic rendering pygame.font.Font.metrics() Get the detailed parameters of each character in the stringpygame.font.Font.get_italic() Check whether the text is rendered in italicspygame.font .Font.get_linesize() Get the line height of font textpygame.font.Font.get_height() Get the height of the fontGet the distance from the top of the font to the baselineGet the distance from the bottom of the font to the baseline
This function creates a rendered text Surface object
This function returns the size required to render text. The return value is a One-tuple (width,height)##pygame.font.Font.set_underline()
pygame.font.Font.get_underline()
pygame.font.Font.set_bold()
##pygame.font.Font.get_ascent()
pygame.font.Font.get_descent()
<blockquote><p>使用上述方法,我们可以非常方便地对字体进行渲染,或者获取字体的相关信息,比如字体的高度、是否是粗体、斜体等信息。</p></blockquote><p>上述方法中使用最多要数第一个方法,它是绘制文本内容的关键方法,其语法格式如下:</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>render(text, antialias, color, background=None)</pre><div class="contentsignin">Copy after login</div></div><p>参数说明如下:</p><ul class=" list-paddingleft-2"><li><p><code>text : 要绘制的文本内容

  • antialias : 布尔值参数,是否是平滑字体(抗锯齿)。

  • color : 设置字体颜色;

  • background : 可选参数,默认为 None,该参数用来设置字体的背景颜色。

  • 下面看一组简单的示例:

    import sys
    import pygame
    
    # 初始化
    pygame.init()
    screen = pygame.display.set_mode((600, 400))
    # 填充主窗口的背景颜色
    screen.fill((20, 90, 50))
    # 设置窗口标题
    pygame.display.set_caption(&#39;Python自学网&#39;)
    # 字体文件路径 C:/Windows/Fonts/simhei.ttf
    f = pygame.font.Font(&#39;C:/Windows/Fonts/simhei.ttf&#39;, 50)
    # render(text, antialias, color, background=None) -> Surface
    text = f.render("网址:python.net", True, (255, 0, 0), (255, 255, 255))
    # 获得显示对象的 rect区域大小
    textRect = text.get_rect()
    # 设置显示对象居中
    textRect.center = (300, 200)
    screen.blit(text, textRect)
    while True:
        # 循环获取事件,监听事件
        for event in pygame.event.get():
            # 判断用户是否点了关闭按钮
            if event.type == pygame.QUIT:
                # 卸载所有pygame模块
                pygame.quit()
                # 终止程序
                sys.exit()
        pygame.display.flip()  # 更新屏幕内容
    Copy after login

    除了使用上述方法之外,Pygame 为了增强字体模块的功能,在新的版本中又加入了另外一个字体模块,它就是 Freetype 模块。该模块属于 Pygame 的高级模块, 它能够完全可以取代 Font 模块,并且在 Font 模块的基础上又添加了许多新功能,比如调整字符间距离,字体垂直模式以及逆时针旋转文本等(详情可阅读官方文档)。

    如果想 Freetype 模块,必须使用以下方式导包:

    import pygame.freetype
    Copy after login

    下面使用 Freetype 模块来绘制文本内容,代码如下:

    import sys, pygame
    import pygame.freetype
    
    pygame.init()
    # 设置位置变量
    pos = [180, 50]
    # 设置颜色变量
    GOLD = 255, 251, 0
    BLACK = 0, 0, 0
    screen = pygame.display.set_mode((600, 400))
    pygame.display.set_caption("Python自学网")
    f1 = pygame.freetype.Font("C:/Users/Administrator/Desktop/willhar_.ttf", 45)
    # 注意,这里使用render_to() 来绘制文本内容,与render 相比,该方法无返回值
    # 参数说明:
    # pos 绘制文本开始的位置,fgcolor表示前景色,bgcolor表示背景色,rotation表示文本旋转的角度
    freeRect = f1.render_to(screen, pos, "I love python.net", fgcolor=GOLD, bgcolor=BLACK, rotation=35)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            pygame.display.update()
    Copy after login

    The above is the detailed content of Python's Pygame Font module - how to use text and fonts?. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

    MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

    How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

    The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

    How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

    MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

    HadiDB: A lightweight, horizontally scalable database in Python HadiDB: A lightweight, horizontally scalable database in Python Apr 08, 2025 pm 06:12 PM

    HadiDB: A lightweight, high-level scalable Python database HadiDB (hadidb) is a lightweight database written in Python, with a high level of scalability. Install HadiDB using pip installation: pipinstallhadidb User Management Create user: createuser() method to create a new user. The authentication() method authenticates the user's identity. fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

    Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

    It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

    Does mysql need the internet Does mysql need the internet Apr 08, 2025 pm 02:18 PM

    MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

    Can mysql workbench connect to mariadb Can mysql workbench connect to mariadb Apr 08, 2025 pm 02:33 PM

    MySQL Workbench can connect to MariaDB, provided that the configuration is correct. First select "MariaDB" as the connector type. In the connection configuration, set HOST, PORT, USER, PASSWORD, and DATABASE correctly. When testing the connection, check that the MariaDB service is started, whether the username and password are correct, whether the port number is correct, whether the firewall allows connections, and whether the database exists. In advanced usage, use connection pooling technology to optimize performance. Common errors include insufficient permissions, network connection problems, etc. When debugging errors, carefully analyze error information and use debugging tools. Optimizing network configuration can improve performance

    Does mysql need a server Does mysql need a server Apr 08, 2025 pm 02:12 PM

    For production environments, a server is usually required to run MySQL, for reasons including performance, reliability, security, and scalability. Servers usually have more powerful hardware, redundant configurations and stricter security measures. For small, low-load applications, MySQL can be run on local machines, but resource consumption, security risks and maintenance costs need to be carefully considered. For greater reliability and security, MySQL should be deployed on cloud or other servers. Choosing the appropriate server configuration requires evaluation based on application load and data volume.

    See all articles