PyGTK:我如何使图像自动缩放以适应其父窗口小部件? [英] PyGTK: How do I make an image automatically scale to fit it's parent widget?

查看:116
本文介绍了PyGTK:我如何使图像自动缩放以适应其父窗口小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PyGTK应用程序,需要加载一个未知尺寸的图像,但是我遇到了这样的问题:如果图像非常大或很小,窗口布局就会变形并难以使用。我需要一些使图像自动缩放以适应其父部件的方法。不幸的是,在做了一些研究之后,似乎没有内置代码或其他代码可以做我正在寻找的代码。



我怎么能写点东西去做这个?我原以为有人会为此写一些代码;有没有我错过的东西?

解决方案

您可以使用widget.get_allocation()来查找父窗口小部件的大小, pixbuf.scale_simple缩放图像,如下所示:

 分配= parent_widget.get_allocation()
desired_width =分配。宽度
desired_height = allocation.height

PIXBUF = gtk.gdk.pixbuf_new_from_file( 'your_image.png')
PIXBUF = pixbuf.scale_simple(desired_width,desired_height,gtk.gdk。 INTERP_BILINEAR)
image = gtk.image_new_from_pixbuf(pixbuf)

如果您想要缩放图片每次调整窗口大小时,都必须将上面的代码(或类似的东西,以避免每次从磁盘加载图像)放入与父窗口小部件的size_allocate信号相关的函数中。为避免无限循环,请确保放入小部件的图像不会再次改变其大小。

参考文献:


I have a PyGTK app that needs to load an image of unknown size, however I am having the problem that if the image is either very big or very small, the window layout becomes distorted and hard to use. I need some way of making the image automatically scale to fit its parent widget. Unfortunately, after doing some research, it seems there is no code, built in or otherwise, that does what I'm looking for.

How could I go about writing something to do this? I would have thought that somebody would have written some code for this already; is there something that I missed?

解决方案

You can use widget.get_allocation() to find out the size of the parent widget and pixbuf.scale_simple to scale the image, like this:

allocation = parent_widget.get_allocation()
desired_width = allocation.width
desired_height = allocation.height

pixbuf = gtk.gdk.pixbuf_new_from_file('your_image.png')
pixbuf = pixbuf.scale_simple(desired_width, desired_height, gtk.gdk.INTERP_BILINEAR)
image = gtk.image_new_from_pixbuf(pixbuf)

If you want the image to scale each time the window is resized, you'll have to put the code above (or something similar, to avoid loading the image from disk every time) in a function connected to the size_allocate signal of the parent widget. To avoid infinite loops, make sure that the image you put in the widget doesn't alter its size again.

References:

这篇关于PyGTK:我如何使图像自动缩放以适应其父窗口小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆