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

标签 python gtk pygtk

我在可调整大小的窗口中有一个 GtkImage 小部件和一个引用 GdkPixBuf 存储我想要填充 GtkImage 的图像。

我可以使用此方法缩放 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 方法绑定(bind)到窗口的 configure-event GTK 事件。在窗口的每次大小变化之后,图像确实被适本地缩放。但是我对这个解决方案有两个问题:

  • 我只能把 window 变大。一旦图像被放大,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, widget, event, data=None):
        gtk.main_quit()
        return False

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

希望这对你有帮助,问候

关于python - 使用 (Py)GTK 在调整大小时自动缩放图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4939734/

相关文章:

python - 有什么办法可以防止在循环中打开多个 gz 文件时出现 MemoryError 吗?

python - 在 Python 中检测计算机/程序关闭?

winapi - 使用sigc和glib的win32应用程序如何实现消息循环

python - 如何将主题应用于 PyGTK 应用程序

c++ - 父类方法中不兼容的 cv 限定符

python - 如何将焦点放在 Gtk.TreeView 的特定单元格上?

python - 如何在 pygtk 中创建新信号

python - 如何去除图像的白色背景并使其透明?

python - 如何在没有使用 python 的按键事件的情况下在内部更新/重绘 GTK 小部件 (GTKLabel)?

python - 在另一个训练操作中运行训练操作