微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 pygame 和字体修复此错误

如何解决如何使用 pygame 和字体修复此错误

import pygame,sys

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

coordinate = pygame.mouse.get_pos()

screen = pygame.display.set_mode((1000,800),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))

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(坐标,真,(255,255)) 类型错误:文本必须是 unicode 或字节。 我使用的是 Python 3.9.1

解决方法

需要进行一些更改:

  1. coordinate = pygame.mouse.get_pos() 返回变量 coordinate 分配给的元组。 font.render() 方法将字符串作为参数而不是元组。所以首先你需要渲染 str(coordinate) 而不仅仅是 coordinate,它实际上是一个元组。您可以阅读有关在 pygame here
  2. 中渲染字体的更多信息
text = font.render(str(coordinate),True,(255,255,255)) #Rendering the str(coordinate)
  1. 仅执行第一步不会使您的代码正常运行,您的代码中仍然存在一些问题。要将鼠标的坐标 blit 到屏幕上,您需要在每一帧处获取鼠标坐标。为此,您需要将 coordinate = pygame.mouse.get_pos() 行放在 while True 循环中,同时您还需要将此行 text = font.render(str(coordinate),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),255))
    #[...] other part of code

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

import pygame,sys

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



screen = pygame.display.set_mode((1000,800),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),255)) #Rendering the str(coordinate)
    screen.fill((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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。