Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mouse Position Python Tkinter

Is there a way to get the position of the mouse and set it as a var?

like image 676
Kyle Pfromer Avatar asked Apr 08 '14 00:04

Kyle Pfromer


People also ask

How do I install Tkinter?

The simplest method to install Tkinter in a Windows environment is to download and install either ActivePython 3.8 or 3.7 from here. Alternatively, you can create and activate a Conda environment with Python 3.7 or greater that is integrated with the latest version of Tkinter.

What is cursor in Tkinter?

Python Tkinter supports quite a number of different mouse cursors available. The exact graphic may vary according to your operating system. Here is the list of interesting ones − "arrow" "circle"

How do I get the mouse position in Python?

To determine the mouse's current position, we use the statement, pyautogui. position(). This function returns a tuple of the position of the mouse's cursor. The first value is the x-coordinate of where the mouse cursor is.


1 Answers

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.

like image 144
unutbu Avatar answered Oct 11 '22 08:10

unutbu