Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- import tkinter as tk
- from PIL import ImageGrab
- class RegionSelector:
- def __init__(self, root):
- self.root = root
- self.root.title("Region Selector")
- self.canvas = tk.Canvas(root, cursor="cross")
- self.canvas.pack(fill=tk.BOTH, expand=True)
- self.select_region_button = tk.Button(root, text="Select Region", command=self.start_selection)
- self.select_region_button.pack(pady=10)
- self.selecting_region = False
- self.start_x = None
- self.start_y = None
- def start_selection(self):
- self.selecting_region = True
- self.root.iconify()
- self.root.update()
- self.canvas.bind("<ButtonPress-1>", self.start_drawing)
- self.canvas.bind("<B1-Motion>", self.draw_marker)
- self.canvas.bind("<ButtonRelease-1>", self.finish_selection)
- def start_drawing(self, event):
- self.start_x = self.canvas.canvasx(event.x)
- self.start_y = self.canvas.canvasy(event.y)
- def draw_marker(self, event):
- if not self.selecting_region:
- return
- current_x = self.canvas.canvasx(event.x)
- current_y = self.canvas.canvasy(event.y)
- self.canvas.delete("marker")
- self.canvas.create_rectangle(self.start_x, self.start_y, current_x, current_y, outline="red", tags="marker")
- def finish_selection(self, event):
- if not self.selecting_region:
- return
- self.selecting_region = False
- x, y, w, h = self.get_coordinates()
- print(f"Selected region: x={x}, y={y}, width={w}, height={h}")
- self.root.deiconify()
- screenshot = ImageGrab.grab(bbox=(x, y, x + w, y + h))
- screenshot.save("capture.png")
- self.canvas.unbind("<ButtonPress-1>")
- self.canvas.unbind("<B1-Motion>")
- self.canvas.unbind("<ButtonRelease-1>")
- self.canvas.delete("marker")
- def get_coordinates(self):
- bbox = self.canvas.bbox("marker")
- if bbox:
- x1, y1, x2, y2 = bbox
- return x1, y1, x2 - x1, y2 - y1
- else:
- return 0, 0, 0, 0
- if __name__ == "__main__":
- root = tk.Tk()
- root.geometry("400x300")
- app = RegionSelector(root)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement