GtkFileChooserDialog with image preview
<p>How to create an image preview in a <code>GtkFileChooserDialog</code>?</p>

<p>Here is a simple ChooserDialog:</p>

<pre><code>#!/usr/bin/env python3

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

filechooserdialog = Gtk.FileChooserDialog()
filechooserdialog.set_title("FileChooserDialog")
filechooserdialog.add_button("_Open", Gtk.ResponseType.OK)
filechooserdialog.add_button("_Cancel", Gtk.ResponseType.CANCEL)
filechooserdialog.set_default_response(Gtk.ResponseType.OK)

response = filechooserdialog.run()

if response == Gtk.ResponseType.OK:
    print("File selected: %s" % filechooserdialog.get_filename())

filechooserdialog.destroy()
</code></pre>

<p>How to add a image preview?</p>

<p>GtkFileChooser provides the <a href="https://developer.gnome.org/gtk3/stable/GtkFileChooser.html#gtk-file-chooser-set-preview-widget" rel="nofollow">set_preview_widget</a> function. You create a GtkImage, set it as the preview widget, and update the image whenever the <code>update-preview</code> signal is emitted:</p>

<pre><code>from gi.repository import GdkPixbuf

preview_image= Gtk.Image()
filechooserdialog.set_preview_widget(preview_image)

def update_preview(dialog):
    path= dialog.get_preview_filename()
    try:
        pixbuf= GdkPixbuf.Pixbuf.new_from_file(path)
    except Exception:
        dialog.set_preview_widget_active(False)
    else:
        #scale the image
        maxwidth, maxheight= 300.0, 700.0 # as floats to avoid integer division in python2
        width, height= pixbuf.get_width(), pixbuf.get_height()
        scale= min(maxwidth/width, maxheight/height)
        if scale&lt;1:
            width, height= int(width*scale), int(height*scale)
            pixbuf= pixbuf.scale_simple(width, height, GdkPixbuf.InterpType.BILINEAR)

        preview_image.set_from_pixbuf(pixbuf)
        dialog.set_preview_widget_active(True)
filechooserdialog.connect('update-preview', update_preview)
</code></pre>

python gtk