python auto save printscreen

孤街浪徒 提交于 2019-12-11 22:06:00

问题


Iv'e recently started learning python programming and ran into some problems with my first program. It's a program that auto-saves print screens.

If i have a print screen saved in clipboard and start the program it outputs a .png file. if i start the program with nothing in clipboard and then press print screen it outputs a .png file.

But if i press print screen after the program has already printed a .png file it does absolutely nothing. Can't even use ctrl+c to copy text.

This is the code im using.

from PIL import ImageGrab
from Tkinter import Tk
import time

r = Tk()

while True:

    try:
        im = ImageGrab.grabclipboard()
        date = time.strftime("%Y-%m-%d %H.%M.%S")
        im.save(date + ".png")
        r.clipboard_clear()
    except IOError:
        pass
    except AttributeError:
        pass

回答1:


Two points:

  1. When using Tkinter it already has a mainloop (e.g. while True:). When you create your own main loop, you prevent Tkinter from doing the processing it should.

  2. If you want to actually register a hotkey, there are several ways to do it.

What you'll actually want to do is something more along the lines of this:

import Tkinter as tk
from PIL import Image, ImageGrab

root = tk.Tk()
last_image = None

def grab_it():
    global last_image
    im = ImageGrab.grabclipboard()
    # Only want to save images if its a new image and is actually an image.
    # Not sure if you can compare Images this way, though - check the PIL docs.
    if im != last_image and isinstance(im, Image):
        last_image = im
        im.save('filename goes here')
    # This will inject your function call into Tkinter's mainloop.
    root.after(100, grab_it) 

grab_it() # Starts off the process



回答2:


you should use grab() if you want to take a image of the screen

from PIL import ImageGrab
im = ImageGrab.grab()
im.save("save.png")


来源:https://stackoverflow.com/questions/17832717/python-auto-save-printscreen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!