带有图像预览的 GtkFileChooserDialog
GtkFileChooserDialog with image preview
如何在 GtkFileChooserDialog
中创建图像预览?
这是一个简单的选择器对话框:
#!/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()
如何添加图片预览?
GtkFileChooser 提供set_preview_widget 函数。您创建一个 GtkImage,将其设置为预览小部件,并在发出 update-preview
信号时更新图像:
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<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)
如何在 GtkFileChooserDialog
中创建图像预览?
这是一个简单的选择器对话框:
#!/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()
如何添加图片预览?
GtkFileChooser 提供set_preview_widget 函数。您创建一个 GtkImage,将其设置为预览小部件,并在发出 update-preview
信号时更新图像:
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<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)