简体   繁体   English

在 tkinter 屏幕上执行 ImageGrab

[英]Performing ImageGrab on tkinter Screen

I am trying to save a tkinter screen to a file (to later convert into a video).我正在尝试将 tkinter 屏幕保存到文件(稍后转换为视频)。

I can't get the correct position of the canvas for using ImageGrab.我无法获得使用 ImageGrab 的画布的正确位置。

My relevant imports are:我的相关进口是:

import tkinter
import pyscreenshot as ImageGrab 

I am trying to save the screen using (after drawing the screen):我正在尝试使用(绘制屏幕后)保存屏幕:

grab = ImageGrab.grab(bbox=canvas.bbox())
ImageGrab.grab_to_file(fileName,grab)

I don't know how to get the canvas position for using "ImageGrab.grab".我不知道如何获取使用“ImageGrab.grab”的画布位置。

Is there any way to get the bounding box for the whole canvas, so as to later use ImageGrab to store a screenshot?有没有办法获取整个画布的边界框,以便以后使用ImageGrab存储屏幕截图?

---Edit------------------------------------------------------------------ ---编辑---------------------------------------------- --------------------

Solution:解决方案:

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)

You have methods like winfo_x() , winfo_y() to get position inside parent widget (it doesn't have to be main window), and winfo_rootx() , winfo_rooty() to get position on screen.你有像winfo_x()winfo_y()来获取父小部件内的位置(它不必是主窗口),以及winfo_rootx()winfo_rooty()来获取屏幕上的位置。

Effbot.org: Basic Widget Methods Effbot.org:基本小部件方法

Code displays canvas' position on screen and inside parent Frame代码在屏幕上和父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()

Example result示例结果

--- 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM