[Tutor] saving Tkinter canvas as jpg
eryksun
eryksun at gmail.com
Mon Dec 9 08:10:39 CET 2013
On Sun, Dec 8, 2013 at 8:49 PM, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
>
> https://pypi.python.org/pypi/Pillow/ is a fork of PIL. I've never used it
> myself but here's hoping!!!
ImageGrab has built-in support for Microsoft Windows only:
https://github.com/python-imaging/Pillow/blob/2.2.1/PIL/ImageGrab.py#L29
https://github.com/python-imaging/Pillow/blob/2.2.1/_imaging.c#L3365
https://github.com/python-imaging/Pillow/blob/2.2.1/display.c#L313
A Tk canvas supports saving to a PostScript file, if that suffices
(i.e. if you can render PostScript as an image):
canvas.postscript(file='filename.ps', colormode='color')
http://www.tcl.tk/man/tcl8.5/TkCmd/canvas.htm#M51
OS X includes a screencapture utility that you could call with the
subprocess module:
http://ss64.com/osx/screencapture.html
This answer on Stack Overflow uses the OS X CoreGraphics API:
http://stackoverflow.com/a/13026264/205580
http://pythonhosted.org/pyobjc/apinotes/Quartz.html
Or you could switch to a GUI toolkit with better support for saving
images, such as Qt:
https://qt-project.org/doc/qt-4.8/qpixmap.html
https://qt-project.org/doc/qt-4.8/qpainter.html
Here's a really basic example using PyQt4. Clicking on the "Capture"
button paints the widget to a pixmap that's then saved to "spam.png"
and the desktop to "screenshot.jpg" with 95% quality.
import sys
from PyQt4 import QtCore, QtGui
class Spam(QtGui.QWidget):
def __init__(self):
super(Spam, self).__init__()
self.setGeometry(100, 100, 300, 225)
self.setWindowTitle("Spam")
self.btncap = QtGui.QPushButton("Capture", self)
self.btncap.clicked.connect(self.capture)
self.show()
def paintEvent(self, event):
p = QtGui.QPainter(self)
p.setFont(QtGui.QFont("Times", 20))
flags = QtCore.Qt.AlignBottom | QtCore.Qt.AlignRight
p.drawText(event.rect(), flags, "Spam")
def capture(self):
wid = app.desktop().winId()
QtGui.QPixmap.grabWidget(self).save(
"spam.png", "png")
QtGui.QPixmap.grabWindow(wid).save(
"screenshot.jpg", "jpg", 95)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
spam = Spam()
sys.exit(app.exec_())
More information about the Tutor
mailing list