I am facing a pretty strange behavior of Python MSS library when using inside Tkinter GUI.
I have a Tkinter window that has a button for popping up a TopLevel window. Inside that TopLevel window, I have a button for taking a screenshot (using MSS). Everything works as supposed for the first time, but the problem happens when I destroy (close TopLevel window) and then open it again to take another screenshot. Then it throws an exception that you will be able to see below. And this only happens when I destroy that TopLevel window and try again.
Edit: it seems the problem is somehow related to Ubuntu (using 20.04), because the problem doesn't exists on Win10.
Exception code:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.8/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
File "example.py", line 10, in take_screenshot
with mss.mss() as sct:
File "/home/aivaras/Desktop/freelancing/darius/venv/lib/python3.8/site-packages/mss/factory.py", line 41, in mss
return linux.MSS(**kwargs)
File "/home/aivaras/Desktop/freelancing/darius/venv/lib/python3.8/site-packages/mss/linux.py", line 305, in __init__
self.root = self.xlib.XDefaultRootWindow(self._get_display(display))
File "/home/aivaras/Desktop/freelancing/darius/venv/lib/python3.8/site-packages/mss/linux.py", line 191, in validate
raise ScreenShotError(err, details=details)
mss.exception.ScreenShotError: XDefaultRootWindow() failed
The simplified Tkinter code:
import tkinter as tk
import mss
import mss.tools
def take_screenshot():
with mss.mss() as sct:
screen_part = {"top": 370, "left": 1090, "width": 80, "height": 390}
sct_img = sct.grab(screen_part)
mss.tools.to_png(sct_img.rgb, sct_img.size, output="./output.png")
def create_top_level_win():
top_level_win = tk.Toplevel(root)
take_screenshot_btn = tk.Button(top_level_win, text="Take screenshot", command=take_screenshot)
take_screenshot_btn.pack()
root = tk.Tk()
btn = tk.Button(root, text="Open TopLevel", command=create_top_level_win)
btn.pack()
root.mainloop()