Advertisement
Rnery

Tkinter grab..

Dec 30th, 2023
1,465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.27 KB | Source Code | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. import tkinter as tk
  5. from PIL import ImageGrab
  6.  
  7. class RegionSelector:
  8.     def __init__(self, root):
  9.         self.root = root
  10.         self.root.title("Region Selector")
  11.         self.canvas = tk.Canvas(root, cursor="cross")
  12.         self.canvas.pack(fill=tk.BOTH, expand=True)
  13.         self.select_region_button = tk.Button(root, text="Select Region", command=self.start_selection)
  14.         self.select_region_button.pack(pady=10)
  15.         self.selecting_region = False
  16.         self.start_x = None
  17.         self.start_y = None
  18.  
  19.     def start_selection(self):
  20.         self.selecting_region = True
  21.         self.root.iconify()
  22.         self.root.update()
  23.         self.canvas.bind("<ButtonPress-1>", self.start_drawing)
  24.         self.canvas.bind("<B1-Motion>", self.draw_marker)
  25.         self.canvas.bind("<ButtonRelease-1>", self.finish_selection)
  26.  
  27.     def start_drawing(self, event):
  28.         self.start_x = self.canvas.canvasx(event.x)
  29.         self.start_y = self.canvas.canvasy(event.y)
  30.  
  31.     def draw_marker(self, event):
  32.         if not self.selecting_region:
  33.             return
  34.         current_x = self.canvas.canvasx(event.x)
  35.         current_y = self.canvas.canvasy(event.y)
  36.         self.canvas.delete("marker")
  37.         self.canvas.create_rectangle(self.start_x, self.start_y, current_x, current_y, outline="red", tags="marker")
  38.  
  39.     def finish_selection(self, event):
  40.         if not self.selecting_region:
  41.             return
  42.         self.selecting_region = False
  43.         x, y, w, h = self.get_coordinates()
  44.         print(f"Selected region: x={x}, y={y}, width={w}, height={h}")
  45.         self.root.deiconify()
  46.         screenshot = ImageGrab.grab(bbox=(x, y, x + w, y + h))
  47.         screenshot.save("capture.png")
  48.         self.canvas.unbind("<ButtonPress-1>")
  49.         self.canvas.unbind("<B1-Motion>")
  50.         self.canvas.unbind("<ButtonRelease-1>")
  51.         self.canvas.delete("marker")
  52.  
  53.     def get_coordinates(self):
  54.         bbox = self.canvas.bbox("marker")
  55.         if bbox:
  56.             x1, y1, x2, y2 = bbox
  57.             return x1, y1, x2 - x1, y2 - y1
  58.         else:
  59.             return 0, 0, 0, 0
  60.  
  61. if __name__ == "__main__":
  62.     root = tk.Tk()
  63.     root.geometry("400x300")
  64.     app = RegionSelector(root)
  65.     root.mainloop()
  66.  
Tags: python python3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement