脚本主要实现以下功能:
- 按ctrl开始截图,点击两个坐标,保存截图
- tk输出截图文本信息,文本输出内容倒序处理
- 默认命名为A0自增。支持自定义名称,自增编号,修改自定义名称自增重新计算
- 清空文本框内容
from pynput import mouse, keyboard
from PIL import ImageGrab
import tkinter as tk# 使用字典来维护每个自定义名称的截图计数
screenshot_counts = {}def start_screenshot(text_widget, name_entry):positions = []def on_click(x, y, button, pressed):if not pressed:# 当鼠标松开时记录位置positions.append((x, y))text_widget.insert('1.0', f'坐标为{x},{y}\n')# 如果已经记录了两个位置,就停止监听if len(positions) == 2:return False# 开始监听鼠标with mouse.Listener(on_click=on_click) as listener:listener.join()if len(positions) == 2:# 确保截图区域的坐标是正确的left = min(positions[0][0], positions[1][0])top = min(positions[0][1], positions[1][1])right = max(positions[0][0], positions[1][0])bottom = max(positions[0][1], positions[1][1])# 使用PIL的ImageGrab模块的grab函数来截图screenshot = ImageGrab.grab((left, top, right, bottom))# 获取用户输入的名称screenshot_name = name_entry.get()# 如果用户没有输入名称,使用默认的名称"A"if screenshot_name == "":screenshot_name = "A"# 检查名称是否存在于字典中,如果不存在,初始化计数值if screenshot_name not in screenshot_counts:screenshot_counts[screenshot_name] = 0# 根据名称获取对应的计数值count = screenshot_counts[screenshot_name]screenshot_name_with_count = f"{screenshot_name}{count}.png"# 保存截图screenshot.save(screenshot_name_with_count)text_widget.insert('1.0', f'截图已保存为{screenshot_name_with_count}\n')text_widget.insert('1.0', f'#--------\n')text_widget.insert('1.0', f'\n')# 增加对应名称的截图计数screenshot_counts[screenshot_name] += 1def on_release(key, text_widget, name_entry):if key == keyboard.Key.esc:# 当按下esc键时停止监听return Falseelif key == keyboard.Key.ctrl_l:# 当按下ctrl键时开始截图text_widget.insert('1.0', '开始截图\n')start_screenshot(text_widget, name_entry)def clear_text(text_widget):text_widget.delete(1.0, tk.END)# 创建tkinter窗口
root = tk.Tk()
root.geometry('145x180')
text_widget = tk.Text(root, height=10, width=20)
text_widget.pack()
name_entry = tk.Entry(root)
name_entry.pack()
clear_button = tk.Button(root, text="清空文本框", command=lambda: clear_text(text_widget))
clear_button.pack()# 开始监听键盘
with keyboard.Listener(on_release=lambda key: on_release(key, text_widget, name_entry)) as listener:root.mainloop()
如有帮助,请多多支持作者! 你鼓励是我最大的动力~QAQ~