1

I am creating a python script which has blurred background. Here's the code:

from tkinter import Tk, PhotoImage, Label, Button
from tkinter.constants import BOTH
from PIL import ImageFilter
import pyautogui as pg
import os
import threading as th

root = Tk()
root.title("Blur window")
root.resizable(0, 0)


def place_center():
    global x, y
    reso = pg.size()
    rx = reso[0]
    ry = reso[1]
    x = int((rx/2) - (500/2))
    y = int((ry/2) - (500/2))
    root.geometry(f"500x500+{x}+{y}")

def blur():
    while True:
        img = pg.screenshot(region=(root.winfo_x(), root.winfo_y(), 500, 500))
        try:
            img = img.filter(ImageFilter.GaussianBlur(10))
            img.save("C:\\Users\\username\\AppData\\Local\\Temp\\blurred_bg.png")
            bgimg = PhotoImage(file="C:\\Users\\username\\AppData\\Local\\Temp\\blurred_bg.png")
            bg.config(image=bgimg)
        except Exception:
            pass

place_center()

bg = Label(root, image='')
bg.pack(fill=BOTH, expand=1)

th.Thread(target=blur).start()

root.mainloop()

When I run the program, the window takes screenshot of itself, which I don't want. I want it to take screenshot of the content exactly behind the window.

I tried using root.attributes("-alpha") before and after using the screenshot, but that looks odd.

Here's a short video of the running program

Any suggestions/help will be appreciated. Thank you!

IJ_123
  • 457
  • 6
  • 13
  • 1
    First of all there is no need to save the picture before making it into a `PhotoImage`. Please look at `PIL.ImageTk.PhotoImage` for more details. Second of all, using `tkinter` functions in other threads can cause serious problems unless you really know what you are doing. Third of all, you can use `root.withdraw()` to hide the window then `root.deiconify()` to show the window but that will add a lot of flicking to your window with your current code. – TheLizzard Aug 05 '21 at 09:12
  • Also you can use `root.winfo_screenwidth` and `root.winfo_screenheight` instead of `pg.size()`. `PIL` also has a way of taking screenshots so you might be able to avoid using `pyautogui` – TheLizzard Aug 05 '21 at 09:14
  • 1
    There may be a *fake* way: take the full screen shot before showing the window, then just extract the required region from the shot to update the image on the window after moving the window. – acw1668 Aug 05 '21 at 09:37

0 Answers0