使用(Py)GTK调整大小时自动缩放图像

我在一个可调整大小的窗口中有一个Gtk Image小部件,并且存储了我想要填充GtkImage的图像的参考GdkPixBuf.

我可以使用此方法缩放GdkPixBuf以填充GtkImage小部件:

def update_image(self,widget=None,data=None):
    # Get the size of the source pixmap
    src_width,src_height = self.current_image.get_width(),self.current_image.get_height()

    # Get the size of the widget area
    widget = self.builder.get_object('image')
    allocation = widget.get_allocation()
    dst_width,dst_height = allocation.width,allocation.height

    # Scale preserving ratio
    scale = min(float(dst_width)/src_width,float(dst_height)/src_height)
    new_width = int(scale*src_width)
    new_height = int(scale*src_height)
    pixbuf = self.current_image.scale_simple(new_width,new_height,gtk.gdk.INTERP_BILINEAR)

    # Put the generated pixbuf in the GtkImage widget
    widget.set_from_pixbuf(pixbuf)

当我手动调用update_image时,它按预期工作.现在我希望在调整GtkImage小部件时自动进行缩放.我带来的最佳解决方案是将update_image方法绑定到窗口的configure-event GTK事件.在窗口的每次尺寸改变之后,图像确实被适当地缩放.但是我对此解决方案有两个问题:

>我只能让窗户更大.一旦图像被放大,GTK将不会让我调整窗口的大小,因为窗口不能小于其窗口小部件.我明白为什么它会这样,但我不知道如何改变这种行为.
>也许这没什么大不了的,但我更喜欢GtkImage小部件而不是顶级窗口的事件.

我很抱歉这个小问题的长期解释,我希望你能帮助我.

解决方法

我相信你可以使用小部件的 expose-event信号进行图像缩放.另外,将图像添加到可滚动容器中可以解决窗口调整大小的问题.请检查下面的示例是否适合您.
import gtk

class ScaleImage:
    def __init__(self):
        self.temp_height = 0
        self.temp_width = 0

        window = gtk.Window(gtk.WINDOW_TOPLEVEL)

        image = gtk.Image()
        image.set_from_file('/home/my_test_image.jpg')
        self.pixbuf = image.get_pixbuf()
        image.connect('expose-event',self.on_image_resize,window)    

        Box = gtk.ScrolledWindow()
        Box.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
        Box.add(image)

        window.add(Box)
        window.set_size_request(300,300)
        window.show_all()        

    def on_image_resize(self,widget,event,window):
        allocation = widget.get_allocation()
        if self.temp_height != allocation.height or self.temp_width != allocation.width:
            self.temp_height = allocation.height
            self.temp_width = allocation.width
            pixbuf = self.pixbuf.scale_simple(allocation.width,allocation.height,gtk.gdk.INTERP_BILINEAR)
            widget.set_from_pixbuf(pixbuf)

    def close_application(self,data=None):
        gtk.main_quit()
        return False

if __name__ == "__main__":
    ScaleImage()
    gtk.main()

希望这有帮助,问候

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...