How do I offset the mouse by the window's corner?

Viewed 61

In a project I am making, a dot follows your mouse within the window. The issue is that the dot is going to the mouse relative to the top left of the monitor, NOT the top left of the window. This makes the cursor way off. Here's what my code looks like.

import pygame
import tkinter
root = tkinter.Tk()
pygame.init()
screen = pygame.display.set_mode((480, 360))
dot_image = pygame.image.load("dot.png").convert_alpha()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            break
    x = root.winfo_pointerx() - root.winfo_rootx()
    y = root.winfo_pointery() - root.winfo_rooty()
    screen.fill([0, 64, 64])
    screen.blit(dot_image, (x, y))
    pygame.display.update()
    pygame.time.Clock().tick(60)

I have tried subtracting root.winfo_pointery() by the root.winfo_rooty(), or adding by it, but neither does anything. I have searched how to get mouse relative to window, and got this, but it doesn't work for me. It DOES follow the top left of the screen to a tee though!

1 Answers

Do not mix different frameworks. In pygame, the current position of the mouse can be determined via pygame.mouse.get_pos(). The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed() returns a list of Boolean values ​​that represent the state (True or False) of all mouse buttons.

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
clock = pygame.time.Clock()

dot_image = pygame.image.load("dot.png").convert_alpha()

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
            
    x, y = pygame.mouse.get_pos()
    screen.fill([0, 64, 64])
    screen.blit(dot_image, (x, y))
    pygame.display.update()
    clock.tick(60)

pygame.quit()
Related