views:

58

answers:

2

I'm trying to grab a screenshot every 30 seconds and display it on my GUI, heres what I've got so far.

Code:

from Tkinter import *
from PIL import ImageGrab

window = Tk()

box = (100,100,400,400)
MyImage = ImageGrab.grab(box)

MyPhotoImage = PhotoImage(file=MyImage) #I know this is where its going wrong, just not sure how to fix it
PictureLabel = Label(window, image=MyPhotoImage)
PictureLabel.pack()

window.mainloop()

Python doesnt like the fact I haven't saved the image, is there a possible way to do this without saving the image (not much point since its being renewed every 30 seconds)

Its also not saving every 30 seconds yet, is there a simple way to do this without the program hanging? As I could just use a time.sleep(30) but the program would just freeze up for 30 seconds take a picture then freeze again.

Thanks :)

A: 

You should be able to use StringIO for this:

import cStringIO
fp = cStringIO.StringIO()
MyImage.save(fp,'GIF')
MyPhotoImage = PhotoImage(data=fp.getvalue())

EDITS

Looks like I should read the docs a little closer. The PhotoImage data must be encoded to base64

from Tkinter import *
from PIL import ImageGrab
import cStringIO, base64

window = Tk()

box = (100,100,500,500)
MyImage = ImageGrab.grab(box)

fp = cStringIO.StringIO()
MyImage.save(fp,'GIF')    

MyPhotoImage = PhotoImage(data=base64.encodestring(fp.getvalue())) 
PictureLabel = Label(image=MyPhotoImage)
PictureLabel.pack()
PictureLabel.image = MyPhotoImage

window.mainloop()
Mark
Tried this and it works with no errors, but theres no image showing. Still tinkering around to find the problem.
code_by_night
See edits above.
Mark
awesome it worked, thanks for the help :)
code_by_night
A: 

tk images accept a "data" option, which allows you to specify image data encoded in base64. Also, PIL gives you ways to copy and paste image data. It should be possible to copy the data from MyImage to MyPhotoImage. Have you tried that?

Bryan Oakley
Not quite sure what you mean, how exactly would I copy the data from MyImage to MyPhotoImage.I just tried "MyPhotoImage = PhotoImage(copy=MyImage)", but it did not work.
code_by_night