我正在尝试将TKINTER屏幕保存到文件(以后转换为视频)。
我无法获得使用ImageGrab的画布的正确位置。
我的相关进口是:
import tkinter
import pyscreenshot as ImageGrab
我试图使用(绘制屏幕后)保存屏幕:
grab = ImageGrab.grab(bbox=canvas.bbox())
ImageGrab.grab_to_file(fileName,grab)
我不知道如何获得使用" ImageGrab.grab"的画布位置。
有什么方法可以获取整个画布的边界框,以便以后使用imageGrab存储屏幕截图?
---编辑-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
解决方案:
box = (canvas.winfo_rootx(),canvas.winfo_rooty(),canvas.winfo_rootx()+canvas.winfo_width(),canvas.winfo_rooty() + canvas.winfo_height())
grab = ImageGrab.grab(bbox = box)
grab.save(file_path)
您有诸如winfo_x()
,winfo_y()
之类的方法,可以在父母窗口内获取位置(它不必是主窗口),而winfo_rootx()
,winfo_rooty()
可以在屏幕上获得位置。
effbot.org:基本的小部件方法
代码在屏幕上和parent Frame
import tkinter as tk
def callback():
print(' root.geometry:', root.winfo_geometry())
print('canvas.geometry:', canvas.winfo_geometry())
print('canvas.width :', canvas.winfo_width())
print('canvas.height:', canvas.winfo_height())
print('canvas.x:', canvas.winfo_x())
print('canvas.y:', canvas.winfo_y())
print('canvas.rootx:', canvas.winfo_rootx())
print('canvas.rooty:', canvas.winfo_rooty())
root = tk.Tk()
tk.Label(root, text='SOME WIDGETS IN ROOT').pack()
frame = tk.Frame(root)
frame.pack()
tk.Label(frame, text='SOME WIDGETS IN FRAME').pack()
canvas = tk.Canvas(frame, bg='green')
canvas.pack()
print('n--- before mainloop start---n')
callback()
print('n--- after mainloop start ---n')
root.after(100, callback)
root.mainloop()
示例结果
--- before mainloop start ---
root.geometry: 1x1+0+0
canvas.geometry: 1x1+0+0
canvas.width : 1
canvas.height: 1
canvas.x: 0
canvas.y: 0
canvas.rootx: 0
canvas.rooty: 0
--- after mainloop start ---
root.geometry: 380x303+770+462
canvas.geometry: 380x267+0+18
canvas.width : 380
canvas.height: 267
canvas.x: 0
canvas.y: 18
canvas.rootx: 770
canvas.rooty: 498