How to Get a Window or Fullscreen Screenshot in Python 3k? (without PIL)

后端 未结 4 1316
醉酒成梦
醉酒成梦 2020-12-05 01:05

With python 3, I\'d like to get a handle to another window (not part of my application) such that I can either:

a) directly capture that window as a scre

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 01:44

    This will take a new opened window and make a screenshot of it and then crop it with PIL also possible to find your specific window with pygetwindow.getAllTitles() and then fill in your window name in z3 to get screenshot of only that window.

    If you definitely not want to use PIL you can maximize window with pygetwindow module and then make a screenshot with pyautogui module.

    Note: not tested on Windows XP (but tested on Windows 10)

    import pygetwindow
    import time
    import os
    import pyautogui
    import PIL
    
    # get screensize
    x,y = pyautogui.size()
    print(f"width={x}\theight={y}")
    
    x2,y2 = pyautogui.size()
    x2,y2=int(str(x2)),int(str(y2))
    print(x2//2)
    print(y2//2)
    
    # find new window title
    z1 = pygetwindow.getAllTitles()
    time.sleep(1)
    print(len(z1))
    # test with pictures folder
    os.startfile("C:\\Users\\yourname\\Pictures")
    time.sleep(1)
    z2 = pygetwindow.getAllTitles()
    print(len(z2))
    time.sleep(1)
    z3 = [x for x in z2 if x not in z1]
    z3 = ''.join(z3)
    time.sleep(3)
    
    # also able to edit z3 to specified window-title string like: "Sublime Text (UNREGISTERED)"
    my = pygetwindow.getWindowsWithTitle(z3)[0]
    # quarter of screen screensize
    x3 = x2 // 2
    y3 = y2 // 2
    my.resizeTo(x3,y3)
    # top-left
    my.moveTo(0, 0)
    time.sleep(3)
    my.activate()
    time.sleep(1)
    
    # save screenshot
    p = pyautogui.screenshot()
    p.save(r'C:\\Users\\yourname\\Pictures\\\\p.png')
    
    # edit screenshot
    im = PIL.Image.open('C:\\Users\\yourname\\Pictures\\p.png')
    im_crop = im.crop((0, 0, x3, y3))
    im_crop.save('C:\\Users\\yourname\\Pictures\\p.jpg', quality=100)
    
    # close window
    time.sleep(1)
    my.close()
    

提交回复
热议问题