首页 > 解决方案 > 当 Tkinter 窗口不在顶层时,如何制作它的截图?

问题描述

我正在尝试制作用 Tkinter 制作的窗口的屏幕截图,但是当窗口不在顶层时,我只会得到我在屏幕上看到的内容。我宁愿拥有窗口本身的屏幕截图,即使它上面还有其他窗口。

这是一个最小的例子。我刚刚做了一个用 ImageGrab 保存屏幕截图的功能。当我单击 File.screenshot 或单击 hello 按钮时调用的函数。该功能使用了 2 秒的暂停,就像我有时间在 Tkinter 之上获得另一个窗口一样。

最后我想要的是 Tkinter 窗口的图像,而不是我的屏幕图像。例如,如果我在顶部放置另一个窗口,我会得到:在此处输入图像描述

   from tkinter import *
   from PIL import ImageGrab
   import time
   top = Tk()
   top.geometry("600x400")
   def helloCallBack():
          time.sleep(2)
          x = top.winfo_rootx()
          y = top.winfo_rooty()
          xx = x + top.winfo_width()
          yy = y + top.winfo_height()
          print(x,y,xx,yy)
          ImageGrab.grab(bbox=(x, y, xx, yy)).save("screenImage2.jpg")

   menuBar = Menu(top)
   menuFile = Menu(menuBar, tearoff=0)
   menuFile.add_command(label="Screenshot", command=helloCallBack)
   menuBar.add_cascade( label="File", menu=menuFile)
   top.config(menu = menuBar)
   B = Button(top, text = "Hello", command = helloCallBack)
   B.place(x = 50,y = 50)
   top.mainloop()

标签: pythontkinterscreenshot

解决方案


推荐阅读