python auto save printscreen

2019-09-03 05:56发布

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

2条回答
一纸荒年 Trace。
2楼-- · 2019-09-03 06:35

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")
查看更多
贼婆χ
3楼-- · 2019-09-03 06:38

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
查看更多
登录 后发表回答