0

I am unable to track the mouse event correctly in tkinter with grid management. To simplify the question, I generated a simple example of what I have. Basically, its a tkinter window with labels in grid. For some reason though, the mouse x and y coordinates only go up to ~100 (x) and ~100 (y) and resets back to zero. The x and y coordinates should go to around 0 - 200 for both. Because the window should have 4 labels with about 100x100 (pixels). In short the mouse seems to be tracking per grid (label), not the entire window.

import Tkinter as tk

SIZE = 2
root = tk.Tk()

def motion(event):
    x, y = event.x, event.y
    print('{}, {}'.format(x, y))

def create_labels():
    for r in range(SIZE):
        for c in range(SIZE):
            label = tk.Label(root,
                             text="",
                             bg="gray",
                             width=100,
                             height=50,
                             borderwidth=1,
                             font=("Helvetica", 1))

            label.grid(row=r, column=c)

create_labels()
root.bind('<Motion>', motion)
root.mainloop()
user1179317
  • 2,693
  • 3
  • 34
  • 62
  • 1
    Possible duplicate of [Mouse Position Python Tkinter](https://stackoverflow.com/questions/22925599/mouse-position-python-tkinter) - I think the high value unaccepted answer is what you want. – wwii Jun 16 '19 at 14:02

1 Answers1

2

Because of the way tkinter does events, binding an event to the root window automatically binds it to every window. When your binding fires, event.x and event.y represent the x/y coordinate within the widget that gets the event. Thus, as you move over each label, the coordinates are relative to that widget.

If you want to get the coordinates relative to the root window, use event.x_root and event.y_root.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685