You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Python中为图像标记点并将坐标保存至数据库?

Solution: Add Red Dots, Display Coordinates, and Save to Database

Got it, let's tweak your code to hit all your requirements—adding red dots on click, showing coordinates on the left, and saving those coords to a database. Here's the updated version with breakdowns of each change:

Updated Code

from Tkinter import *
from tkFileDialog import askopenfilename
import Image, ImageTk
import sqlite3

def init_database():
    # Set up a simple SQLite database (swap to MySQL/postgres if needed later)
    conn = sqlite3.connect('click_coords.db')
    cursor = conn.cursor()
    # Create table if it doesn't exist yet
    cursor.execute('''CREATE TABLE IF NOT EXISTS coordinates
                 (id INTEGER PRIMARY KEY AUTOINCREMENT, x INTEGER, y INTEGER)''')
    conn.commit()
    conn.close()

def save_to_db(x, y):
    # Save the clicked coordinates to the database
    conn = sqlite3.connect('click_coords.db')
    cursor = conn.cursor()
    cursor.execute("INSERT INTO coordinates (x, y) VALUES (?, ?)", (x, y))
    conn.commit()
    conn.close()

if __name__ == "__main__":
    # Initialize the database first
    init_database()
    
    root = Tk()
    root.title("Image Click Tracker")
    
    # Split the window into two sections: left for coords, right for image
    main_container = Frame(root)
    main_container.pack(fill=BOTH, expand=1)
    
    # Left panel to display coordinates
    coord_panel = Frame(main_container, bd=2, relief=GROOVE, padx=15, pady=15)
    coord_panel.pack(side=LEFT, fill=Y)
    
    instruction_label = Label(coord_panel, text="Click the image to see coordinates!", font=('Arial', 12))
    instruction_label.pack(pady=20)
    
    x_display = Label(coord_panel, text="X: ", font=('Arial', 14))
    x_display.pack(pady=5)
    
    y_display = Label(coord_panel, text="Y: ", font=('Arial', 14))
    y_display.pack(pady=5)
    
    # Right panel with image canvas and scrollbars
    image_frame = Frame(main_container, bd=2, relief=SUNKEN)
    image_frame.pack(side=RIGHT, fill=BOTH, expand=1)
    image_frame.grid_rowconfigure(0, weight=1)
    image_frame.grid_columnconfigure(0, weight=1)
    
    x_scroll = Scrollbar(image_frame, orient=HORIZONTAL)
    x_scroll.grid(row=1, column=0, sticky=E+W)
    y_scroll = Scrollbar(image_frame)
    y_scroll.grid(row=0, column=1, sticky=N+S)
    
    canvas = Canvas(image_frame, bd=0, xscrollcommand=x_scroll.set, yscrollcommand=y_scroll.set)
    canvas.grid(row=0, column=0, sticky=N+S+E+W)
    
    x_scroll.config(command=canvas.xview)
    y_scroll.config(command=canvas.yview)
    
    # Load and display the image
    file_path = askopenfilename(parent=root, initialdir="C:/", title='Choose an image.')
    img = Image.open(file_path)
    tk_image = ImageTk.PhotoImage(img)
    canvas.create_image(0, 0, image=tk_image, anchor="nw")
    canvas.config(scrollregion=canvas.bbox(ALL))
    
    # Keep a reference to the image to avoid Tkinter garbage collection
    canvas.image = tk_image
    
    # Handle mouse click events
    def handle_click(event):
        # Get accurate coordinates (accounting for scroll position)
        actual_x = canvas.canvasx(event.x)
        actual_y = canvas.canvasy(event.y)
        
        # Update the left panel with current coordinates
        x_display.config(text=f"X: {int(actual_x)}")
        y_display.config(text=f"Y: {int(actual_y)}")
        
        # Draw a small red dot at the click location (5px diameter)
        canvas.create_oval(actual_x-2, actual_y-2, actual_x+2, actual_y+2, fill='red', outline='red')
        
        # Save the coordinates to the database
        save_to_db(int(actual_x), int(actual_y))
        
        # Print to console for debugging
        print(f"Clicked at: X={actual_x}, Y={actual_y}")
    
    # Bind left mouse click to our handler
    canvas.bind("<Button-1>", handle_click)
    
    root.mainloop()

Key Changes Explained

  • Database Setup: Added init_database() to create a SQLite database and table on first run, plus save_to_db() to store each click's coordinates. SQLite is lightweight and works without a separate server, which is perfect for this use case.
  • Left Coordinate Panel: Added a dedicated frame on the left to show real-time X/Y values using labels that update every time you click.
  • Red Dot Marker: Used canvas.create_oval() to draw a tiny red dot exactly where you click. We use canvasx()/canvasy() to adjust for scrollbar position, so the dot always lines up with your cursor.
  • Image Fix: Stored the tk_image as a canvas attribute to prevent Tkinter from deleting the image (a common gotcha with Tkinter and PIL).

Quick Notes

  • For Python 3, adjust the imports:
    • Replace from Tkinter import * with from tkinter import *
    • Replace from tkFileDialog import askopenfilename with from tkinter.filedialog import askopenfilename
    • Replace import Image, ImageTk with from PIL import Image, ImageTk (install Pillow first with pip install pillow)
  • To view saved coordinates, run this quick snippet:
    import sqlite3
    conn = sqlite3.connect('click_coords.db')
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM coordinates")
    print(cursor.fetchall())
    conn.close()
    

内容的提问来源于stack exchange,提问作者kotich-io

火山引擎 最新活动