在 Tkinter GUI 中使用时,我面临着 Python MSS 库的一个非常奇怪的行为。
我有一个 Tkinter 窗口,它有一个用于弹出 TopLevel 窗口的按钮。在 TopLevel 窗口中,我有一个用于截屏的按钮(使用 MSS)。一切都是第一次按预期工作,但是当我销毁(关闭 TopLevel 窗口)然后再次打开它以获取另一个屏幕截图时会出现问题。然后它会抛出一个异常,您将能够在下面看到。这只发生在我销毁该 TopLevel 窗口并重试时。
编辑:似乎问题与 Ubuntu(使用 20.04)有关,因为 Win10 上不存在该问题。
异常代码:
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
简化的 Tkinter 代码:
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()