一、python调用gtk实现屏幕截图

1、开发环境

        操作系统:linux

        开发语言:python 2.7

        需要提前装好的库:gtk、time、os

2、安装gtk模块

sudo apt-get install python-gtk2-dev python-gtk2-tutorial

3、实现代码

# !/usr/bin/python
# coding=UTF-8

import gtk.gdk
import time
import os

# 在没有png目录时,创建一个png目录
absPath = os.path.abspath('.')
path = [x for x in os.listdir('.') if os.path.isdir(x)]
# print(path)
if 'png' in path:
    pass
else:
    # 创建目录png
    pngPath = os.path.join(absPath,'png')
    os.mkdir(pngPath)

# 截图
def screening():
    # 获取当前时间
    nowtime = time.strftime('%Y_%m_%d_%H_%M_%S',time.localtime(time.time()))
    w = gtk.gdk.get_default_root_window()
    # 获取当前屏幕尺寸
    sz = w.get_size()
    print "The size of the window is %d x %d" % sz
    # 获取屏幕像素颜色
    pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
    # 抓取指定区域
    pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
    if (pb != None):
        # 抓取的图片保存在png目录下,命名规则:当前时间,属性:png
        pb.save("png/"+r'%s.png' %(nowtime),"png")
        # 将抓取的图片追加记录在screening.txt文件中
        with open("screen_log.txt","a+") as screen_log:
            screen_log.writelines(nowtime)
            screen_log.writelines("\n")
            # 释放资源
            screen_log.close()
        print "Screenshot saved to png."
    else:
        print "Unable to get the screenshot."
while True:
    screening()
    # 获取抓取图片的记录次数
    count=len(open('screen_log.txt','r').readlines())
    # 将抓取图片的统计数写入number.txt文件中
    with open("number.txt","w") as number:
        number.write(str(count))
        # 释放资源
        number.close()
    # 定时10秒
    time.sleep(10)

二、python使用PIL的ImageGrab模块实现屏幕截图

1、开发环境

        操作系统:windows

        开发语言:python 3

        编译工具:pycharm

        库:PIL

2、实现代码

# python3 author linzhongyunwu

import time
from PIL import ImageGrab
import os

# 在没有png目录时,创建一个png目录
absPath = os.path.abspath('.')
path = [x for x in os.listdir('.') if os.path.isdir(x)]
# print(path)
if 'png' in path:
    #print('yes')
    pass
else:
    #print('no')
    #创建目录
    pngPath = os.path.join(absPath,'png')
    os.mkdir(pngPath)

#截屏
def Screening():
    nowtime = time.strftime('%Y_%m_%d_%H_%M_%S',time.localtime(time.time()))
    print(nowtime)
    # 截屏
    im = ImageGrab.grab()
    # 保存
    im.save(r'png\%s.png' %(nowtime))
    with open("screen_log.txt","a+",newline="") as screen_log:
        screen_log.writelines(nowtime)
        screen_log.writelines("\n")
        screen_log.close()
# count=0
while True:
    # print("截图!")
    Screening()
    # print("暂停")
    # print("\n")
    # count += 1
    count=len(open('screen_log.txt','r').readlines())
    with open("number.txt","w",newline="") as number:
        number.write(str(count))
        number.close()
    time.sleep(10) #定时10s看一下