Files
douyi_guaji_main/tools/pick_coords.py
T
Your Name 02b2930639 Add styles for web UI and create batch script for launching Web GUI
- Introduced a comprehensive CSS file for styling the web interface, including variables for colors, layout styles, and responsive design adjustments.
- Added a batch script to automate the process of stopping any existing instances of the web GUI and launching the new instance, along with opening the browser to the appropriate URL.
2025-12-15 18:17:16 +08:00

155 lines
5.0 KiB
Python

import sys
from pathlib import Path
from typing import Optional
from PIL import Image, ImageTk
try:
import tkinter as tk
from tkinter import filedialog
except Exception as e:
raise SystemExit(f"tkinter 不可用:{e}\n请安装带 tkinter 的 Python,或改用画图/PS/GIMP 取坐标。")
def clamp(v: float, lo: float, hi: float) -> float:
return lo if v < lo else hi if v > hi else v
class CoordPicker:
def __init__(self, image_path: Optional[Path]):
self.image_path: Optional[Path] = None
self.img: Optional[Image.Image] = None
self.w = 0
self.h = 0
self.scale = 1.0
self.disp_w = 0
self.disp_h = 0
self.tk_img = None
self.root = tk.Tk()
# 菜单 + 快捷键
menubar = tk.Menu(self.root)
file_menu = tk.Menu(menubar, tearoff=0)
file_menu.add_command(label="打开...", command=self.open_dialog, accelerator="Ctrl+O")
file_menu.add_separator()
file_menu.add_command(label="退出", command=self.root.destroy)
menubar.add_cascade(label="文件", menu=file_menu)
self.root.config(menu=menubar)
self.root.bind_all("<Control-o>", lambda e: self.open_dialog())
self.canvas = tk.Canvas(self.root, width=800, height=600)
self.canvas.pack(fill=tk.BOTH, expand=False)
self._canvas_image_id = self.canvas.create_image(0, 0, anchor=tk.NW)
self.status = tk.StringVar()
self.status.set("移动鼠标查看坐标;单击复制坐标;Ctrl+O 打开图片")
self.label = tk.Label(self.root, textvariable=self.status, anchor="w")
self.label.pack(fill=tk.X)
self.canvas.bind("<Motion>", self.on_move)
self.canvas.bind("<Button-1>", self.on_click)
if image_path is None:
if not self.open_dialog():
raise SystemExit(2)
else:
self.set_image(image_path)
def set_image(self, image_path: Path) -> None:
image_path = Path(image_path)
self.image_path = image_path
self.img = Image.open(image_path).convert("RGB")
self.w, self.h = self.img.size
# 显示用缩放(不改变输出坐标)
screen_w = self.root.winfo_screenwidth()
screen_h = self.root.winfo_screenheight()
max_w = int(screen_w * 0.9)
max_h = int(screen_h * 0.85)
scale_w = max_w / max(1, self.w)
scale_h = max_h / max(1, self.h)
self.scale = min(1.0, scale_w, scale_h)
self.disp_w = int(self.w * self.scale)
self.disp_h = int(self.h * self.scale)
disp_img = self.img
if self.scale < 1.0:
disp_img = self.img.resize((self.disp_w, self.disp_h), Image.BICUBIC)
self.tk_img = ImageTk.PhotoImage(disp_img)
self.canvas.config(width=self.disp_w, height=self.disp_h)
self.canvas.itemconfig(self._canvas_image_id, image=self.tk_img)
self.root.title(f"取坐标: {image_path} ({self.w}x{self.h})")
def open_dialog(self) -> bool:
initial_dir = None
try:
if self.image_path and self.image_path.parent.exists():
initial_dir = str(self.image_path.parent)
except Exception:
initial_dir = None
filename = filedialog.askopenfilename(
title="选择图片",
initialdir=initial_dir,
filetypes=[
("Images", "*.png;*.jpg;*.jpeg;*.bmp;*.webp"),
("All files", "*.*"),
],
)
if not filename:
return False
try:
self.set_image(Path(filename))
return True
except Exception as e:
self.status.set(f"打开失败: {e}")
return False
def _to_image_xy(self, event) -> tuple[int, int]:
if not self.img or self.w <= 0 or self.h <= 0:
return 0, 0
x = int(clamp(event.x / self.scale, 0, self.w - 1))
y = int(clamp(event.y / self.scale, 0, self.h - 1))
return x, y
def on_move(self, event):
x, y = self._to_image_xy(event)
self.status.set(f"x={x}, y={y}")
def on_click(self, event):
x, y = self._to_image_xy(event)
text = f"{x},{y}"
print(text)
try:
self.root.clipboard_clear()
self.root.clipboard_append(text)
self.status.set(f"已复制: {text}")
except Exception:
self.status.set(f"坐标: {text} (复制失败)")
def run(self):
self.root.mainloop()
def main(argv: list[str]) -> int:
p: Optional[Path] = None
if len(argv) >= 2:
p = Path(argv[1]).expanduser()
if not p.is_absolute():
p = (Path(__file__).resolve().parent.parent / p).resolve()
if not p.exists():
print(f"找不到图片: {p}")
print("将弹出文件选择框,请手动选择图片。")
p = None
else:
print("未传入图片路径,将弹出文件选择框。")
CoordPicker(p).run()
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv))