【问题标题】:How to fix this error with pygame and fonts [duplicate]如何使用 pygame 和字体修复此错误 [重复]
【发布时间】:2021-03-02 04:27:16
【问题描述】:
import pygame, sys

pygame.init()
clock = pygame.time.Clock()

coordinate = pygame.mouse.get_pos()

screen = pygame.display.set_mode((1000,800), 0, 32)
pygame.display.set_caption("Mouse Tracker")

font = pygame.font.Font(None, 25)
text = font.render(coordinate, True, (255,255,255))

while True:

screen.fill((0,0,0))

screen.blit(text, (10, 10))


for event in pygame.event.get():
    if event.type == QUIT:
        pygame.quit()
        sys.exit()

pygame.display.update()
clock.tick(60)

我正在尝试制作一个程序来跟踪您的鼠标并在屏幕上显示它的坐标。我收到一条错误消息: text = font.render(坐标, True, (255,255,255)) TypeError:文本必须是 unicode 或字节。 我正在使用 Python 3.9.1

【问题讨论】:

    标签: python pygame mouse tracking


    【解决方案1】:

    需要进行一些更改:

    1. coordinate = pygame.mouse.get_pos() 返回一个元组,变量 coordinate 被分配到该元组。 font.render() 方法将字符串作为参数而不是元组。所以首先你需要渲染 str(coordinate) 而不仅仅是 coordinate 这实际上是一个元组。您可以阅读更多关于在 pygame here 中渲染字体的信息
    text = font.render(str(coordinate), True, (255,255,255)) #Rendering the str(coordinate)
    
    1. 仅靠第一步不会使您的代码正常运行,您的代码中仍然存在一些问题。为了将鼠标的坐标传送到屏幕上,您需要在每一帧获取鼠标坐标。为此,您需要将coordinate = pygame.mouse.get_pos() 行放在while True 循环中,此外,您还需要将此行text = font.render(str(coordinate), True, (255,255,255)) 放在while 循环中
    import pygame,sys
    #[...]#part of code
    while True:
        coordinate = pygame.mouse.get_pos() #Getting the mouse coordinate at every single frame
        text = font.render(str(coordinate), True, (255,255,255))
        #[...] other part of code
    

    所以最终的工作代码应该看起来像:

    import pygame, sys
    
    pygame.init()
    clock = pygame.time.Clock()
    
    
    
    screen = pygame.display.set_mode((1000,800), 0, 32)
    pygame.display.set_caption("Mouse Tracker")
    
    font = pygame.font.Font(None, 25)
    
    
    while True:
        coordinate = pygame.mouse.get_pos() #Getting the mouse coordinate at every single frame
        text = font.render(str(coordinate), True, (255,255,255)) #Rendering the str(coordinate)
        screen.fill((0,0,0))
    
        screen.blit(text, (10, 10))
    
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:#
                pygame.quit()
                sys.exit()
    
        pygame.display.update()
        clock.tick(60)
    

    【讨论】:

    • 很高兴能帮到你:)
    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多