我在可调整大小的窗口中有一个 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/