Python Tkinter Snip Tool, unable to create a transparent window then 50% transparent selection area

  Kiến thức lập trình

I want to create a snip tool with python, the screen capture window should be 100% transparent and only when the user selects an area, only then that area becomes translucent, let’s say black with 50% opacity. I am unable to create a transparent background with tkinter.

Here is what i have done till now –

import tkinter as tk
import pyautogui
from PIL import ImageGrab, ImageTk
import pytesseract

pytesseract.pytesseract.tesseract_cmd = 'C:\Program Files\Tesseract-OCR\tesseract.exe'

class Overlay:
    def __init__(self, master: tk.Tk):
        self.master = master
        self.master.attributes("-topmost", True)
        # self.master.wm_attributes("-transparentcolor", self.master["bg"])
        self.master.attributes("-fullscreen", True)
        self.master.attributes("-alpha", 0.1)
        # self.master.overrideredirect(True)
        self.canvas = tk.Canvas(master=self.master, cursor="cross",
                                height=self.master.winfo_screenheight(), width=self.master.winfo_screenwidth(), bg="black")
        self.x = None
        self.y = None
        self.selection = None
        self.screenshot = None
        self.canvas.bind("<ButtonPress-1>", self.onPress)
        self.canvas.bind("<B1-Motion>", self.onDrag)
        self.canvas.bind("<ButtonRelease-1>", self.onRelease)
        # self.canvas.bind("<Escape>", self.removeOverlay)

    def configureOpacityTag(self):
        self.canvas.tag_configure("opaque", alpha=0.5)

    def onPress(self, event):
        self.x = self.master.winfo_pointerx()
        self.y = self.master.winfo_pointery()
        if (self.selection):
        self.selection = None

    def onDrag(self, event):
        self.currX = self.master.winfo_pointerx()
        self.currY = self.master.winfo_pointery()
        if (self.selection):
                self.selection, self.x, self.y, self.currX, self.currY)
            self.selection = self.canvas.create_rectangle(
                self.x, self.y, self.currX, self.currY, outline="black", fill="white")

    def onRelease(self, event):
        x1, y1, x2, y2 = self.canvas.coords(self.selection)
        # print(x1, y1, x2, y2)
        selectedBox = (min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2))
        self.screenshot = ImageGrab.grab(bbox=selectedBox)

    def capture(self):

    def removeOverlay(self, event):

New contributor

Sam Ps is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.