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
How to Convert a List of Dictionaries to Json in Python/Django
Calculate Sklearn.Roc_Auc_Score for Multi-Class
Python Login Script; Usernames and Passwords in a Separate File
Anaconda Installed But Cannot Launch Navigator
In Python, How to Check If a Date Is Valid
How to Disable Pylint Unused Import Error Messages in VS Code
Ssl: Certificate_Verify_Failed With Python3
Truth Value of a Series Is Ambiguous. Use A.Empty, A.Bool(), A.Item(), A.Any() or A.All()
Calculating Manhattan Distance in Python in an 8-Puzzle Game
Python: Import Cx_Oracle Importerror: No Module Named Cx_Oracle Error Is Thown
Typeerror: Image Data Can Not Convert to Float
How to Share Data Between a Parent and Forked Child Process in Python
Populating a List in Python Using for Loop
How to Use Installed Packages in Pycharm
Parsing Outlook .Msg Files With Python
Sum a Column Based on Groupby and Condition