使用Python编写截图轻量化工具

这是用Python做到截图工具,不过由于使用了ctypes调用了Windows的API, 同时访问了Windows中”C:/Windows/Cursors/”中的.cur光标样式文件, 这个工具只适用于Windows环境;

如果要提升其跨平台性的话,需要考虑替换ctypes的一些专属于Windows的API以及设置不同的.cur访问方式;

该模块只使用了PIL这一个第三方库,和别的使用pygamepyautogui等模块不同,该工具着重强调轻量化,无关或没必要使用的库尽可能不使用。

目前模块尚未完成,只包含了基本的截图时调整大小,保存,翻页查看不同截图这些简单功能;后续会继续完善,但当前模块的可用性已足够,且代码经过重构,具备一定的可读性以及可拓展性。

完整代码如下,单文件,自行安装PIL模块,在Windows环境上运行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import ctypes
import tkinter as tk
from tkinter import messagebox, filedialog
from PIL import ImageGrab, ImageTk
  
  
ScaleFactor = ctypes.windll.shcore.GetScaleFactorForDevice(0)
ctypes.windll.shcore.SetProcessDpiAwareness(1)
  
  
  
class FlatButton(tk.Label):
    def __init__(
            self, parent, command, enter_fg="#000000",
            click_color="#25C253", *args, **kwargs
        ):
        super().__init__(parent, *args, **kwargs)
        self.__fg = fg = kwargs.get("fg", "#474747")
        self.__enter_fg = enter_fg
        self.__click_fg = click_color
        self.command = command
        self.config(cursor="hand2")
        self.bind("", lambda _: self.config(fg=enter_fg))
        self.bind("", lambda _: self.config(fg=fg))
        self.bind("", lambda _: self.config(fg=click_color))
        self.bind("", self.__command)
        if fg == enter_fg:
            raise ValueError("enter_fg must be different from fg")
  
    def __command(self, event):
        try:
            if self.cget("fg") in (self.__enter_fg, self.__click_fg):
                self.command(event)
            self.config(fg=self.__fg)
        except tk.TclError:
            # Button have been destroy.
            pass
  
  
  
class AdjustableRect(object):
    """
    The judgement seq is so important that you must care about:
    (right, bottom), (left, top), (right, top), (left, bottom),
    (center_x, top), (center_x, bottom), (left, center_y, ), (right, center_y)
    """
    ANCHOR_SIZE = 3
    ANCHOR_HOVER_DISTANCE = 20
    CURSOR_FILES_NAME = ["aero_nwse_l.cur", "aero_nesw_l.cur", "aero_ns_l.cur", "aero_ew_l.cur"]
    CURSOR_FILES = [f"@C:/Windows/Cursors/{cursor_file}" for cursor_file in CURSOR_FILES_NAME]
    CURSORS = [
        CURSOR_FILES[0], CURSOR_FILES[0], CURSOR_FILES[1], CURSOR_FILES[1],
        CURSOR_FILES[2], CURSOR_FILES[2], CURSOR_FILES[3], CURSOR_FILES[3],
        "fleur", "arrow"
    ]
  
    def __init__(self, parent, screenshot):
        self.parent: tk.Canvas = parent
        self.screenshot: ScreenshotUtils = screenshot
        self.__rect: int = 0
        self.__anchors: list[int] = []
        self.anchor_id: int = 0
  
    def rect_coords(self) -> tuple[int, int, int, int]:
        try:
            return self.parent.coords(self.__rect)
        except tk.TclError:
            return [
                min(self.screenshot.start_x, self.screenshot.end_x),
                min(self.screenshot.start_y, self.screenshot.end_y),
                max(self.screenshot.start_x, self.screenshot.end_x),
                max(self.screenshot.start_y, self.screenshot.end_y)
            ]
     
    def anchor_coords(self) -> tuple[int, int, int, int]:
        left, top, right, bottom = self.rect_coords()
        horizontal_middle = (left + right) // 2
        vertical_middle = (top + bottom) // 2
        return (
            (left, top), (horizontal_middle, top), (right, top), (right, vertical_middle),
            (right, bottom), (horizontal_middle, bottom), (left, bottom), (left, vertical_middle)
        )
     
    def get_anchor(self, event) -> int:
        cls = self.__class__
        left, top, right, bottom = self.rect_coords()
        center_x, center_y = (left + right) // 2, (top + bottom) // 2
        def near(actual, target):
            return abs(actual - target)  int:
        return int(ScaleFactor/100*value)
     
    ZOOM: int = 4
    ZOOM_WIDTH: float = TkS(28.75)
    ZOOM_SCREEN_SIZE: int = int(ZOOM_WIDTH*ZOOM)
    MAGNIFIER_OFFSET: int = 36
    AJUST_BAR_WIDTH: int = TkS(100)
  
    # 截图相关变量
    def __init__(self):
        self.start_x = self.start_y = self.end_x = self.end_y = 0
        self.move_start_x = self.move_start_y = self.move_end_x = self.move_end_y = 0
        self.current_image = None
        self.pixel_reader = None
        self.final_images = list()
        # 这种是只移动但不改变大小和内容的控件,只需移动无需重绘
        self.screenshot_move_widget = list()
        # 这种是移动和改变大小的控件,需要实时重绘
        self.screenshot_redraw_widget = list()
  
    @staticmethod
    def TkS(value) -> int:
        return int(ScaleFactor/100*value)
     
    @classmethod
    def move_widget_coords(cls, x, y) -> list[tuple[int, int, int, int]]:
        # 按照主框架,水平线,垂直线的顺序返回坐标
        magnifier_x = x+cls.MAGNIFIER_OFFSET
        magnifier_y = y+cls.MAGNIFIER_OFFSET
        main_frame_coord  = (
            magnifier_x, magnifier_y,
            magnifier_x+cls.ZOOM_SCREEN_SIZE,
            magnifier_y+cls.ZOOM_SCREEN_SIZE
        )
        horrontal_line_coord = (
            magnifier_x, magnifier_y+cls.ZOOM_SCREEN_SIZE // 2,
            magnifier_x+cls.ZOOM_SCREEN_SIZE,
            magnifier_y+cls.ZOOM_SCREEN_SIZE // 2
        )
        vertical_line_coord = (
            magnifier_x+cls.ZOOM_SCREEN_SIZE // 2, magnifier_y,
            magnifier_x+cls.ZOOM_SCREEN_SIZE // 2,
            magnifier_y+cls.ZOOM_SCREEN_SIZE
        )
        coords = [main_frame_coord, horrontal_line_coord, vertical_line_coord]
        return coords
  
    def redraw_widget_coords(self, x, y) -> list[tuple]:
        # 按照"长 × 宽"、"放大镜图像"、"POS标签"、"RGB标签"的顺序返回坐标
        offset = self.__class__.MAGNIFIER_OFFSET
        width_height_info = (min(self.start_x, self.end_x), min(self.start_y, self.end_y) - 40)
        magnifier_coord = (x + offset, y + offset)
        pos_info = (x + offset, y + offset+self.__class__.ZOOM_SCREEN_SIZE + 10)
        rgb_info = (x + offset, y + offset+self.__class__.ZOOM_SCREEN_SIZE + 47)
        coords = [width_height_info, magnifier_coord, pos_info, rgb_info]
        return coords
  
  
  
class MainUI(tk.Tk):
    def __init__(self):
        super().__init__()
        self.screenshot = ScreenshotUtils()
        self.set_window()
        self.menu_bar: tk.Frame = self.set_menubar()
        self.cut_btn: tk.Label = self.set_cut_btn()
        self.save_btn: tk.Label = self.set_save_btn()
        self.turn_left_btn: tk.Label = self.set_turn_left_btn()
        self.turn_right_btn: tk.Label = self.set_turn_right_btn()
        self.show_image_canvas: tk.Canvas = self.set_show_image_canvas()
        self.adjust_rect: AdjustableRect = None
        self.pos_label: tk.Label = None
        self.rgb_label: tk.Label = None
        self.adjust_bar: tk.Frame = None
  
    def set_window(self):
        self.title("截图工具")
        self.geometry(f"{self.screenshot.TkS(240)}x{self.screenshot.TkS(30)}")
  
    def set_menubar(self) -> tk.Frame:
        menubar = tk.Frame(self, bg="#FFFFFF", height=30)
        menubar.pack(fill=tk.X)
        return menubar
  
    def set_cut_btn(self) -> tk.Label:
        btn_cut = FlatButton(
            self.menu_bar, self.start_capture, text="<img draggable="false" role="img" class="emoji" alt="✂" src="https://s.w.org/images/core/emoji/15.0.3/svg/2702.svg">",
            bg="#FFFFFF", font=("Segoe UI Emoji", 18),
        )
        btn_cut.pack(side=tk.LEFT, padx=5)
        return btn_cut
     
    def set_save_btn(self) -> tk.Label:
        btn_save = FlatButton(
            self.menu_bar, self.save_image, text="<img draggable="false" role="img" class="emoji" alt="💾" src="https://s.w.org/images/core/emoji/15.0.3/svg/1f4be.svg">",
            bg="#FFFFFF", font=("Segoe UI Emoji", 18),
        )
        btn_save.pack(side=tk.LEFT, padx=5)
        return btn_save
     
    def set_turn_left_btn(self) -> tk.Label:
        turn_left_btn = FlatButton(
            self.menu_bar, self.turn_page, text="u25C0",
            bg="#FFFFFF", font=("Segoe UI Emoji", 18),
        )
        turn_left_btn.pack(side=tk.LEFT, padx=5)
        return turn_left_btn
  
    def set_turn_right_btn(self) -> tk.Label:
        turn_page_btn = FlatButton(
            self.menu_bar, self.turn_page, text="u25B6",
            bg="#FFFFFF", font=("Segoe UI Emoji", 18),
        )
        turn_page_btn.pack(side=tk.LEFT, padx=5)
        return turn_page_btn
  
    def set_cancel_btn(self, parent) -> tk.Label:
        cancel_btn = FlatButton(
            parent, self.clear_capture_info, text="×", bg="#FFFFFF",
            enter_fg="#DB1A21",fg="#CC181F", font=("微软雅黑", 18)
        )
        cancel_btn.pack(side=tk.RIGHT, padx=5)
        return cancel_btn
  
    def set_confirm_btn(self, parent) -> tk.Label:
        confirm_btn = FlatButton(
            parent, self.confirm_capture, fg="#23B34C", text="√",
            enter_fg="#27C956", bg="#FFFFFF", font=("微软雅黑", 18)
        )
        return confirm_btn
  
    def set_show_image_canvas(self) -> tk.Canvas:
        canvas = tk.Canvas(self, bg="white")
        return canvas
     
    def set_adjust_bar(self) -> tk.Frame:
        self.adjust_bar = tk.Frame(self.full_screenshot_canvas, bg="#FFFFFF", height=50)
        cancel_btn = self.set_cancel_btn(self.adjust_bar)
        confirm_btn = self.set_confirm_btn(self.adjust_bar)
        cancel_btn.pack(side=tk.RIGHT, padx=5)
        confirm_btn.pack(side=tk.RIGHT, padx=10)
     
    def set_magnifier_frame(self, event) -> None:
        initial_coord = (0, 0, 0, 0)
        main_frame_id = self.full_screenshot_canvas.create_rectangle(*initial_coord, outline='#1AAE1A', width=1)
        horrontal_line = self.full_screenshot_canvas.create_line(*initial_coord, fill="#1AAE1A", width=2)
        vertical_line = self.full_screenshot_canvas.create_line(*initial_coord, fill="#1AAE1A", width=2)
        self.screenshot.screenshot_move_widget = [main_frame_id, horrontal_line, vertical_line]
        event.x = event.x + event.widget.winfo_rootx()
        event.y = event.y + event.widget.winfo_rooty()
        self.update_magnifier(event)
  
    def set_full_screenshot_canvas(self, parent) -> tk.Canvas:
        img = ImageGrab.grab()
        self.screenshot.current_image = img
        self.screenshot.pixel_reader = img.convert("RGB")
        photo = ImageTk.PhotoImage(img)
        full_screenshot_canvas = tk.Canvas(parent, bg="white")
        full_screenshot_canvas.create_image(0, 0, anchor=tk.NW, image=photo)
        full_screenshot_canvas.image = photo
        full_screenshot_canvas.pack(fill=tk.BOTH, expand=True)
        return full_screenshot_canvas
     
    def set_pos_rgb_label(self, parent) -> tk.Label:
        label = tk.Label(parent, bg="#000000", font=("微软雅黑", 8), fg="#ffffff")
        return label
  
  
class ScreenshotTool(MainUI):
    def __init__(self):
        super().__init__()
        self.page_index = 0
  
    def start_capture(self, event):
        self.attributes('-alpha', 0)
        self.update()
        self.capture_win = tk.Toplevel()
        self.capture_win.geometry(f"{self.winfo_screenwidth()}x{self.winfo_screenheight()}+0+0")
        self.capture_win.overrideredirect(True)
        self.full_screenshot_canvas = self.set_full_screenshot_canvas(self.capture_win)
        self.pos_label = self.set_pos_rgb_label(self.full_screenshot_canvas)
        self.rgb_label = self.set_pos_rgb_label(self.full_screenshot_canvas)
        self.adjust_rect = AdjustableRect(self.full_screenshot_canvas, self.screenshot)
        self.set_magnifier_frame(event)
        self.set_adjust_bar()
        self.full_screenshot_canvas.bind("", self.on_press)
        self.full_screenshot_canvas.bind("", self.update_magnifier)
        self.full_screenshot_canvas.bind("", self.on_release)
  
    def on_press(self, event):
        self.adjust_rect.on_press(event)
        self.full_screenshot_canvas.unbind("")
        self.full_screenshot_canvas.bind("", self.on_drag)
  
    def on_drag(self, event):
        self.adjust_rect.rect_adjust(event)
        self.update_magnifier(event)
  
    def on_release(self, event, resize=True):
        self.unbind_all()
        self.adjust_rect.on_release(event)
        self.full_screenshot_canvas.config(cursor=self.adjust_rect.CURSOR_FILES[0])
        self.full_screenshot_canvas.bind("", self.start_move)
        self.full_screenshot_canvas.bind("", self.adjust_rect.on_hover)
        self.adjust_bar.place(x=self.screenshot.end_x - 300, y=self.screenshot.end_y + 10, width=300)
        if resize:
            self.screenshot.end_x, self.screenshot.end_y = event.x, event.y
  
    def unbind_all(self):
        events = ("", "", "")
        for event in events:
            self.full_screenshot_canvas.unbind(event)
  
    def update_magnifier(self, event):
        x, y = event.x, event.y
        size = ScreenshotUtils.ZOOM_WIDTH
        img = self.screenshot.current_image.crop((x - size//2, y - size//2, x + size//2, y + size//2))
        img = img.resize((ScreenshotUtils.ZOOM_SCREEN_SIZE, ScreenshotUtils.ZOOM_SCREEN_SIZE))
        photo = ImageTk.PhotoImage(img)
        self.full_screenshot_canvas.image2 = photo
        w, h = abs(self.screenshot.end_x - self.screenshot.start_x), abs(self.screenshot.end_y - self.screenshot.start_y)
        for redraw_widget in self.screenshot.screenshot_redraw_widget:
            self.full_screenshot_canvas.delete(redraw_widget)
        self.screenshot.screenshot_redraw_widget.clear()
        redraw_widget_coords = self.screenshot.redraw_widget_coords(x, y)
        width_height_info, magnifier_coord, pos_info, rgb_info = redraw_widget_coords
        wh_info_widget = self.full_screenshot_canvas.create_text(*width_height_info, anchor=tk.NW, fill="white", text=f"{w} × {h}")
        zoom_img = self.full_screenshot_canvas.create_image(*magnifier_coord, anchor=tk.NW, image=photo)
        self.pos_label.config(text=f"POS: ({x}, {y})")
        self.rgb_label.config(text=f"RGB: {self.screenshot.pixel_reader.getpixel((x, y))}")
        self.pos_label.place(x=pos_info[0], y=pos_info[1])
        self.rgb_label.place(x=rgb_info[0], y=rgb_info[1])
        self.screenshot.screenshot_redraw_widget = [wh_info_widget, zoom_img]
        self.update_magnifier_frame(x, y)
  
    def update_magnifier_frame(self, x: int, y: int) -> None:
        coords = self.screenshot.move_widget_coords(x, y)
        for widget, coord in zip(self.screenshot.screenshot_move_widget, coords):
            self.full_screenshot_canvas.coords(widget, *coord)
            self.full_screenshot_canvas.tag_raise(widget)
  
    def start_move(self, event):
        self.screenshot.move_start_x = event.x
        self.screenshot.move_start_y = event.y
        self.adjust_bar.place_forget()
        self.pos_label.place_forget()
        self.rgb_label.place_forget()
        for widget in self.screenshot.screenshot_redraw_widget:
            self.full_screenshot_canvas.delete(widget)
        for widget in self.screenshot.screenshot_move_widget:
            self.full_screenshot_canvas.tag_lower(widget)
        self.full_screenshot_canvas.bind("", self.adjust_rect.rect_adjust)
        self.full_screenshot_canvas.bind("", lambda e: self.on_release(e, False))
  
    def clear_capture_info(self, _):
        self.capture_win.destroy()
        self.full_screenshot_canvas.destroy()
        self.attributes('-alpha', 1)
        self.screenshot.screenshot_move_widget.clear()
  
    def confirm_capture(self, event):
        self.clear_capture_info(event)
        x1, y1, x2, y2 = self.adjust_rect.rect_coords()
        image = self.screenshot.current_image.crop((x1, y1, x2, y2))
        result = self.show_image(image)
        self.screenshot.final_images.append(result)
        self.page_index = len(self.screenshot.final_images) - 1
        self.attributes('-topmost', 1)
  
    def show_image(self, image):
        self.geometry(f"{max(image.width, ScreenshotUtils.TkS(240))}x{image.height+self.menu_bar.winfo_height()}")
        photo = ImageTk.PhotoImage(image)
        self.show_image_canvas.config(width=image.width, height=image.height)
        self.show_image_canvas.delete("all")
        self.show_image_canvas.create_image(0, 0, anchor=tk.NW, image=photo)
        self.show_image_canvas.image = photo
        self.show_image_canvas.pack()
        return image
  
    def save_image(self, _):
        try:
            image = self.screenshot.final_images[self.page_index]
            filename = filedialog.asksaveasfilename(
                defaultextension=".png",
                filetypes=[("PNG files", "*.png"), ("JPEG files", "*.jpg")],
                initialfile=f"{image.width}x{image.height}.png"
            )
            if not filename:
                return
            image.save(filename)
        except IndexError:
            messagebox.showerror("保存失败", "未检测到截取图像")
  
    def turn_page(self, event):
        if len(self.screenshot.final_images) == 0:
            return messagebox.showinfo("提示", "暂无图片可切换!")
        if event.widget == self.turn_left_btn:
            if self.page_index == 0:
                return messagebox.showinfo("提示", "已经是第一张图片!")
            self.page_index -= 1
        else:
            if self.page_index == len(self.screenshot.final_images) - 1:
                return messagebox.showinfo("提示", "已经是最后一张图片!")
            self.page_index += 1
        self.show_image(self.screenshot.final_images[self.page_index])
  
if __name__ == "__main__":
    app = ScreenshotTool()
    app.mainloop()

到此这篇关于使用Python编写截图轻量化工具的文章就介绍到这了,更多相关Python截图内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/python/14929.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部