0

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
Someone
  • 257
  • 3
  • 12

2 Answers2

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
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
0

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")
der_die_das_jojo
  • 893
  • 1
  • 9
  • 21
  • That's not what i want to do. I want to print out a image everytime print screen is pressed. – Someone Jul 24 '13 at 13:02
  • Here you can see the possible bindings: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm the print-screen is not listed there. i suppose it is handeled by windows/linux and therefor not bindable by a user programm – der_die_das_jojo Jul 24 '13 at 13:37