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)
I am trying to make a program that tracks your mouse and shows the coordinates of it on the sreen. I get an error saying: text = font.render(coordinate, True, (255,255,255))
TypeError: text must be a unicode or bytes.
I am using Python 3.9.1
There are couple of changes to be made:
coordinate = pygame.mouse.get_pos()
returns a tuple which the variable coordinate
is assigned to. The font.render()
method takes a string as an argument not a tuple. So first you need to render the str(coordinate)
and not just the coordinate
which is actually a tuple. You can read more about rendering the font in pygame heretext = font.render(str(coordinate), True, (255,255,255)) #Rendering the str(coordinate)
coordinate = pygame.mouse.get_pos()
in the while True
loop, along with this you also need to place this line text = font.render(str(coordinate), True, (255,255,255))
in the while loopimport 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
So the final working code should look somewhat like:
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)