Tkinter - On which widget is mouse pointer currently?

Viewed 2447

I want to ask u guys if there is a way of getting name or some id of widget which is mouse pointer currently on. Is there a way of doing this? Thanks for any response.

1 Answers

Normally you get this information from a binding. However, if you want to poll the system at any point to find out which widget is under the mouse, you can use winfo_pointerxy to get the coordinates of the mouse, and then pass those to winfo_containing to get the widget under those coordinates.

Here's an example program that continuously prints out the widget under the mouse:

import tkinter as tk

def print_widget_under_mouse(root):
    x,y = root.winfo_pointerxy()
    widget = root.winfo_containing(x,y)
    print("widget:", widget)
    root.after(1000, print_widget_under_mouse, root)

root = tk.Tk()
label_foo = tk.Label(root, text="Foo", name="label_foo")
label_bar = tk.Label(root, text="Bar", name="label_bar")
button = tk.Button(root, text="Button", name="button")

button.pack(side="bottom")
label_foo.pack(fill="both", expand=True)
label_bar.pack(fill="both", expand=True)

print_widget_under_mouse(root)

root.mainloop()
Related