问题描述
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
解决方法
需要进行一些更改:
-
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)
- 仅执行第一步不会使您的代码正常运行,您的代码中仍然存在一些问题。要将鼠标的坐标 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)