Tkinter using a non-saved picture as an image
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 *开发者_StackOverflow社区
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 :)
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()
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?
精彩评论