简体   繁体   中英

Getting the absolute position of cursor in tkinter

So I have a code from my supervisor that I am facing problems in understanding. I wish to draw a rectangle where my cursor is, using the create_rectangle method for which I give arguments/coordinates as:

rect = create_rectangle(x, y, x + 10, y + 10, fill = 'blue', width = 0)

I wish x and y here to be the current coordinates of my cursor with respect to my root window.

The way x and y are calculated in my code before passing them to this function is:

x = root.winfo_pointerx() - root.winfo_rootx()
y = root.winfo_pointery() - root.winfo_rooty()

And I can't for the life of me understand why this has been done. I tried doing just

x = root.winfo_pointerx()
y = root.winfo_pointery()

and also just

x = root.winfo_rootx()
y = root.winfo_rooty()

but neither of these draw the rectangle where the cursor is. I also tried looking into the documentation but can't really understand what's happening.

So why is x = root.winfo_pointerx() - root.winfo_rootx() and y = root.winfo_pointery() - root.winfo_rooty() being done here?

You are asking about the difference between absolute SCREEN and relative mouse pointer's positions.

The notation:

x = root.winfo_pointerx() - root.winfo_rootx()
y = root.winfo_pointery() - root.winfo_rooty()

reflects the mouse pointer's absolute position in contrast with winfo_pointerx() and w.winfo_pointery() (or w.winfo_pointerxy() ) which reflect the mouse pointer's coordinates relatively to your w 's root window .

But what does absolute and relative notions mean?

winfo_rootx() and winfo_rooty() return, respectively, the x and y coordinate sof upper left corner of this widget on the root window. But these x and y coordinates are calculated regarding your laptop's SCREEN

winfo_pointerx() and winfo_pointery() return the x and y coordinates of the mouse pointer relatively to the main root's window NOT to the SCREEN .

So by running only winfo_pointerxy() you are taking in consideration only the root window itself but you are ignoring the rest (the SCREEN ).

But the problem is that when you move your mouse on the root window , you must not forget that your system is calculating the coordinates based on your laptop's SCREEN .

Alternative approach

Note that you can substitute your current code:

def get_absolute_position(event=None):
    x = root.winfo_pointerx() - root.winfo_rootx()
    y = root.winfo_pointery() - root.winfo_rooty()
    return x, y

By an other approach taking advantage from the event's coordinates:

def get_absolute_position(event):
    x = event.x
    y = event.y
    return x, y

Simple:

from tkinter import *
root = Tk()

def f(event):
    print(event.x, event.y)

root.bind("<Motion>", f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM