Mouse Position in Python Tkinter

PythonTkinterServer Side ProgrammingProgramming

Events are very useful to perform and manage multiple tasks in a large-scale application. We can bind a particular event with the keyboard buttons or mouse buttons using the bind(‘handler’, ‘callback’) method. Generally, the mouse pointer and its motion are tracked for the purpose of building a screensaver, 2D or 3D games. In order to print the coordinates of the pointer, we have to bind the Motion with a callback function that gets the position of the pointer in x and y variables.

Example

#Import tkinter library
from tkinter import *
#Create an instance of tkinter frame or window
win= Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
def callback(e):
   x= e.x
   y= e.y
   print("Pointer is currently at %d, %d" %(x,y))
win.bind('<Motion>',callback)
win.mainloop()

Output

Running the above code will print the actual position of the pointer whenever we hover on the window.

On the console, you will get to see the actual position of the mouse pointer as you hover the mouse on the screen.

Pointer is currently at 452, 225
Pointer is currently at 426, 200
Pointer is currently at 409, 187
Pointer is currently at 392, 174
Pointer is currently at 382, 168
Pointer is currently at 378, 163
Pointer is currently at 376, 159
Pointer is currently at 369, 150
Pointer is currently at 366, 141
Pointer is currently at 362, 130
raja
Published on 22-Apr-2021 07:36:57
Advertisements