pythonpygamemousetracking

How to fix this error with pygame and fonts


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


Solution

  • There are couple of changes to be made:

    1. 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 here
    text = font.render(str(coordinate), True, (255,255,255)) #Rendering the str(coordinate)
    
    1. Step one alone won't make your code functional, there are still some problems in your code. For blitting the coordinate of the mouse to the screen, you need to get the mouse coordinates at every single frame. For that to function you need to place the line 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 loop
    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
    

    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)