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

2024-04-16 16:15:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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(坐标,真,(255255)) TypeError:文本必须是unicode或字节。 我正在使用Python 3.9.1


Tags: textimporteventtruecoordinategetinitdisplay
1条回答
网友
1楼 · 发布于 2024-04-16 16:15:38

有几处需要修改:

  1. coordinate = pygame.mouse.get_pos()返回变量coordinate分配给的元组。font.render()方法将字符串作为参数,而不是元组。因此,首先需要呈现str(coordinate),而不仅仅是coordinate,它实际上是一个元组。您可以阅读有关在pygamehere中呈现字体的更多信息
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)

相关问题 更多 >