如何在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.
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
globalkeyword lets us updateL_Click_xandL_Click_yinside the function so they're accessible outside of it. - Event Coordinates:
event.x/event.ygive coordinates relative to the window. If you need screen-wide coordinates, useevent.x_root/event.y_rootinstead. - List Storage: We append tuples of (x,y) to
click_historyevery 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_youtside your function, you probably forgot to declare them asglobal(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

