Mouse Position Python Tkinter

Mouse Position Python Tkinter

You could set up a callback to react to <Motion> events:

import Tkinter as tk
root = tk.Tk()

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

root.bind('<Motion>', motion)
root.mainloop()

I'm not sure what kind of variable you want. Above, I set local variables x and y to the mouse coordinates.

If you make motion a class method, then you could set instance attributes self.x and self.y to the mouse coordinates, which could then be accessible from other class methods.

How to show live mouse position on tkinter window

You can use after() to periodically get the mouse coordinates and update the label.

Below is an example:

import tkinter as tk
import win32api

root = tk.Tk()

mousecords = tk.Label(root)
mousecords.place(x=0, y=0)

def show_mouse_pos():
x, y = win32api.GetCursorPos()
#x, y = mousecords.winfo_pointerxy() # you can also use tkinter to get the mouse coords
mousecords.config(text=f'x : {x}, y : {y}')
mousecords.after(50, show_mouse_pos) # call again 50ms later

show_mouse_pos() # start the update task
root.mainloop()

python tkinter mouse position "bind('<Motion>')" return wrong position

The position is relative to the widget, not the window. When your mouse moves over the listbox, the event goes to the listbox rather than the root window.

If you want the coordinates relative to the window, use e.x_root and e.y_root



Related Topics



Leave a reply



Submit