You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在tkinter中获取鼠标点击事件的(x,y)坐标并作为变量使用

Got it, let's work through this problem—capturing mouse click coordinates, storing them in variables or a list, and being able to use those values elsewhere in your code is totally doable. I'll walk you through two reliable approaches depending on whether you need a GUI window or want to capture clicks anywhere on your screen.

Solution: Capture Mouse Click Coordinates & Store in Variables/List

Approach 1: Using Tkinter (Built-in, GUI-Based)

This uses Python's built-in tkinter library, so no extra installs are needed. It creates a simple window where you can click to capture coordinates, which are stored in both global variables and a list.

Full Example Code

import tkinter as tk

# Initialize a list to track all click coordinates
click_history = []
# Initialize global variables for the last click's coordinates
L_Click_x = None
L_Click_y = None

def handle_left_click(event):
    global L_Click_x, L_Click_y
    # Grab coordinates from the click event
    L_Click_x = event.x
    L_Click_y = event.y
    
    # Add the new coordinates to our history list
    click_history.append((L_Click_x, L_Click_y))
    
    # Optional: Print feedback to verify it's working
    print(f"Left click recorded: ({L_Click_x}, {L_Click_y})")
    print(f"All stored clicks: {click_history}\n")

# Set up the GUI window
root = tk.Tk()
root.title("Click to Capture Coordinates")
root.geometry("700x500")

# Bind left mouse clicks to our handler function
root.bind("<Button-1>", handle_left_click)

# Start the GUI loop (runs until you close the window)
root.mainloop()

# After closing the window, you can still access the stored values
print("=== Final Stored Data ===")
print(f"Last click coordinates: ({L_Click_x}, {L_Click_y})")
print(f"Full click history: {click_history}")

Key Details

  • Global Variables: The global keyword lets us update L_Click_x and L_Click_y inside the function so they're accessible outside of it.
  • Event Coordinates: event.x/event.y give coordinates relative to the window. If you need screen-wide coordinates, use event.x_root/event.y_root instead.
  • List Storage: We append tuples of (x,y) to click_history every time a click happens—this list preserves the order of all your clicks.

Approach 2: Using Pynput (No GUI, Screen-Wide Clicks)

If you don't want a GUI window and need to capture clicks anywhere on your screen, use the pynput library (install it first with pip install pynput).

Full Example Code

from pynput.mouse import Listener

click_history = []
L_Click_x = None
L_Click_y = None

def on_mouse_click(x, y, button, pressed):
    global L_Click_x, L_Click_y
    # Only react to left clicks that are pressed (not released)
    if pressed and button == button.left:
        L_Click_x = x
        L_Click_y = y
        click_history.append((x, y))
        
        print(f"Left click recorded: ({x}, {y})")
        print(f"All stored clicks: {click_history}\n")
        
        # Optional: Stop listening after 3 clicks (remove this line for infinite listening)
        if len(click_history) == 3:
            return False

# Start listening for mouse events
with Listener(on_click=on_mouse_click) as listener:
    listener.join()

# Access stored values after listening stops
print("=== Final Stored Data ===")
print(f"Last click coordinates: ({L_Click_x}, {L_Click_y})")
print(f"Full click history: {click_history}")

Troubleshooting Common Issues

  • Variable Scope Problems: If you couldn't access L_Click_x/L_Click_y outside your function, you probably forgot to declare them as global (or use a class to manage state, which is great for larger projects).
  • List Not Updating: Make sure your list is initialized outside the click handler function—if you define it inside, it'll reset every time a click happens.

Either of these methods will let you capture and store mouse click coordinates, which you can then use in your more complex code.

内容的提问来源于stack exchange,提问作者DHines

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:15:52