Skip to content

Commit 4966426

Browse files
authored
Create screenshot.py
0 parents  commit 4966426

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Diff for: screenshot.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import tkinter as tk
2+
import pyautogui
3+
import datetime
4+
import os
5+
6+
class SnippingApp:
7+
def __init__(self):
8+
self.start_x = self.start_y = self.end_x = self.end_y = 0
9+
self.snipping_frame = tk.Tk()
10+
self.snipping_frame.withdraw() # Hide the main window
11+
self.start_snip()
12+
13+
def start_snip(self):
14+
self.snipping_frame = tk.Tk()
15+
self.snipping_frame.attributes('-fullscreen', True)
16+
self.snipping_frame.attributes('-alpha', 0.3) # Semi-transparent
17+
self.snipping_frame.overrideredirect(True) # Remove window decorations
18+
19+
self.canvas = tk.Canvas(self.snipping_frame, bg='black')
20+
self.canvas.pack(fill=tk.BOTH, expand=tk.YES)
21+
self.canvas.bind('<ButtonPress-1>', self.on_button_press)
22+
self.canvas.bind('<B1-Motion>', self.on_move_press)
23+
self.canvas.bind('<ButtonRelease-1>', self.on_button_release)
24+
25+
def on_button_press(self, event):
26+
self.start_x = self.snipping_frame.winfo_pointerx() - self.snipping_frame.winfo_rootx()
27+
self.start_y = self.snipping_frame.winfo_pointery() - self.snipping_frame.winfo_rooty()
28+
self.canvas.delete("rect")
29+
30+
def on_move_press(self, event):
31+
cur_x = self.snipping_frame.winfo_pointerx() - self.snipping_frame.winfo_rootx()
32+
cur_y = self.snipping_frame.winfo_pointery() - self.snipping_frame.winfo_rooty()
33+
self.canvas.delete("rect")
34+
self.canvas.create_rectangle(self.start_x, self.start_y, cur_x, cur_y, outline="white", width=2, tags="rect")
35+
36+
def on_button_release(self, event):
37+
self.end_x = self.snipping_frame.winfo_pointerx() - self.snipping_frame.winfo_rootx()
38+
self.end_y = self.snipping_frame.winfo_pointery() - self.snipping_frame.winfo_rooty()
39+
self.snipping_frame.withdraw() # Hide the snipping frame
40+
41+
if self.end_x > self.start_x and self.end_y > self.start_y:
42+
take_bounded_screenshot(self.start_x, self.start_y, self.end_x, self.end_y)
43+
44+
def take_bounded_screenshot(x1, y1, x2, y2):
45+
if not os.path.exists("snips"):
46+
os.makedirs("snips")
47+
48+
image = pyautogui.screenshot(region=(x1, y1, x2 - x1, y2 - y1))
49+
file_name = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".png"
50+
image.save(os.path.join("snips", file_name))
51+
52+
if __name__ == "__main__":
53+
app = SnippingApp()
54+
tk.mainloop()

0 commit comments

Comments
 (0)