Tkinter Get Mouse Position

If you’re building a desktop application in Python, there will come a point where you need to know exactly where the user is clicking or moving their mouse.

In my experience of developing Tkinter interfaces, I’ve found that tracking mouse coordinates is essential for creating interactive dashboards, drawing tools, or custom drag-and-drop features.

In this tutorial, I will show you several ways to capture the mouse position in Tkinter, ranging from simple click events to real-time tracking.

The Importance of Mouse Tracking in GUIs

When I first started building tools for data analysts in New York, I realized that static buttons weren’t enough. Users wanted to interact with the canvas directly.

Whether you are building a mapping tool to track logistics across the United States or a simple photo editor, knowing the X and Y coordinates is the backbone of interactivity.

Tkinter makes this surprisingly easy, but there are a few different ways to approach it depending on whether you need the position relative to a specific widget or the entire screen.

Method 1: Get Mouse Position on Click (The bind Method)

This is the most common approach I use. It involves “binding” a specific mouse action (like a left-click) to a function that retrieves the coordinates.

In this example, we’ll create a simple coordinate logger. Imagine you are building a tool for a real estate firm to mark property locations on a floor plan.

How it Works

When you click inside the window, Tkinter generates an event object. This object contains x and y attributes representing the click location.

import tkinter as tk

def show_coordinates(event):
    # Retrieve x and y from the event object
    x_coord = event.x
    y_coord = event.y
    
    # Update the label with the current position
    coord_label.config(text=f"Last Click at (Manhattan Grid): X={x_coord}, Y={y_coord}")
    print(f"User clicked at: {x_coord}, {y_coord}")

# Initialize the main window
root = tk.Tk()
root.title("NYC Real Estate Mapper")
root.geometry("600x400")

# Instruction label
instruction = tk.Label(root, text="Click anywhere to get the building coordinates", pady=20)
instruction.pack()

# Label to display the result
coord_label = tk.Label(root, text="Coordinates: X=0, Y=0", font=("Arial", 14, "bold"))
coord_label.pack(expand=True)

# Bind the Left Mouse Click (<Button-1>) to our function
root.bind("<Button-1>", show_coordinates)

root.mainloop()

I executed the above example code and added the screenshot below.

Tkinter Get Mouse Position

I prefer this method because it is event-driven. Your CPU doesn’t waste cycles constantly checking the mouse; it only reacts when the user actually interacts.

Method 2: Real-Time Mouse Tracking (Motion Sensing)

Sometimes a click isn’t enough. You might need to track the mouse as it moves, perhaps to show a “hover” effect over different states on a US map.

For this, I use the <Motion> event. It triggers every time the mouse moves even a single pixel within the widget.

Why use Motion?

If you’re designing a high-end dashboard for a logistics company in Seattle, you might want to show tooltips that follow the cursor as it moves over different shipping zones.

import tkinter as tk

class USATrackerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Pacific Northwest Logistics Tracker")
        self.root.geometry("800x500")
        
        # Create a drawing canvas simulating a map area
        self.canvas = tk.Canvas(self.root, bg="#f0f0f0", highlightthickness=2, highlightbackground="#333")
        self.canvas.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # Status bar to show live coordinates
        self.status_var = tk.StringVar()
        self.status_var.set("Move mouse over the map area")
        self.status_bar = tk.Label(self.root, textvariable=self.status_var, bd=1, relief=tk.SUNKEN, anchor=tk.W)
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        
        # Bind mouse motion to the canvas
        self.canvas.bind("<Motion>", self.track_motion)

    def track_motion(self, event):
        # Get coordinates relative to the canvas widget
        x, y = event.x, event.y
        self.status_var.set(f"Current GPS Overlay Position: Latitude Offset={y}, Longitude Offset={x}")

if __name__ == "__main__":
    root = tk.Tk()
    app = USATrackerApp(root)
    root.mainloop()

I executed the above example code and added the screenshot below.

Get Mouse Position in Tkinter

When tracking motion, keep your callback function very “light.” If you perform heavy calculations inside a <Motion> bind, your GUI will feel laggy.

Method 3: Get Global Mouse Position (winfo_pointerxy)

There are rare cases where you need the mouse position relative to the entire computer screen, not just the Tkinter window.

I often use this when I’m building multi-window applications where a popup needs to appear exactly where the mouse is, even if the main window isn’t focused.

Use winfo_pointerx() and winfo_pointery()

Tkinter provides built-in methods called winfo_pointerx() and winfo_pointery() that query the operating system for the cursor’s location.

import tkinter as tk

def get_global_pos():
    # Fetch coordinates relative to the entire screen monitor
    global_x = root.winfo_pointerx()
    global_y = root.winfo_pointery()
    
    # Fetch coordinates relative to the root window
    local_x = root.winfo_pointerx() - root.winfo_rootx()
    local_y = root.winfo_pointery() - root.winfo_rooty()
    
    result_label.config(text=f"Global (Screen): {global_x}, {global_y}\nLocal (App): {local_x}, {local_y}")
    
    # Schedule the function to run again after 100ms for a "live" feel
    root.after(100, get_global_pos)

root = tk.Tk()
root.title("Global Cursor Monitor - Austin Tech Lab")
root.geometry("400x200")

result_label = tk.Label(root, text="Fetching data...", font=("Courier", 12))
result_label.pack(expand=True)

# Start the polling loop
get_global_pos()

root.mainloop()

I executed the above example code and added the screenshot below.

Get Tkinter Mouse Position

In my experience, this is perfect for “Color Picker” tools or screen capture utilities where the user’s focus might drift outside the primary application borders.

Method 4: Track Position Relative to the Root Window

One tricky thing about Tkinter is that event.x gives you the position relative to the widget that was clicked.

If you click a button inside a frame, event.x is relative to that button. But what if you need the position relative to the main window (root)?

You can use event.x_root and event.y_root, and then subtract the window’s starting position.

import tkinter as tk

def get_relative_to_root(event):
    # x_root and y_root are always screen-relative
    root_x = event.x_root - root.winfo_rootx()
    root_y = event.y_root - root.winfo_rooty()
    
    print(f"Position relative to the main window: {root_x}, {root_y}")

root = tk.Tk()
root.geometry("500x500")

# Sub-frame to demonstrate relative coordinate shifts
sub_frame = tk.Frame(root, bg="blue", width=200, height=200)
sub_frame.place(x=150, y=150)

# Even if we click the blue box, we want the main window coords
sub_frame.bind("<Button-1>", get_relative_to_root)

root.mainloop()

Handle Mouse Position in Specific Use Cases

I’ve found that different industries in the US have specific needs for mouse tracking. Here are two scenarios I’ve frequently encountered.

Scenario A: Draw on a Canvas

If you’re building a signature pad for a banking app in Charlotte, you’ll want to combine mouse position with the “Left Click + Motion” event.

This allows you to draw lines only when the user is actively clicking and dragging.

Scenario B: Data Visualization

When building charts for an energy company in Houston, you might use mouse coordinates to show a vertical “crosshair” that snaps to the nearest data point on a graph.

Summary of Mouse Events

Here is a quick reference table I use to remember which event to bind:

EventAction
<Button-1>Left mouse button click
<Button-3>Right mouse button click
<Motion>Any mouse movement
<B1-Motion>Moving the mouse while holding the left button
<Enter>Mouse entering the widget area
<Leave>Mouse leaving the widget area

In this article, I have covered the various ways you can retrieve mouse coordinates in Tkinter.

From simple clicks to global screen tracking, these techniques should cover almost any GUI project you are working on.

I hope you found this tutorial helpful! Be sure to experiment with the code samples and integrate them into your own Python applications.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.