我编写了一个扩展Gtk.image的类,根据PyGTK: How do I make an image automatically scale to fit it's parent widget?自动调整父级大小,但有一些改进和更正。
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GdkPixbuf, GLib
class ImageEx(Gtk.Image):
pixbuf = None
def __init__(self, *args, **kwargs):
super(ImageEx, self).__init__(*args, **kwargs)
self.connect("size-allocate", self.on_size_allocate)
self.props = super(ImageEx, self).props
self.props.width_request = 100
self.props.height_request = -1
self.props.hexpand = True
self.tempHeight = 0
self.tempWidth = 0
self.origHeight = 0
self.origWidth = 0
def set_from_pixbuf(self, pixbuf):
self.pixbuf = pixbuf
self.origHeight = pixbuf.get_height()
self.origWidth = pixbuf.get_width()
self.tempHeight = 0
self.tempWidth = 0
self.on_size_allocate(None, self.get_allocation())
def calculateHeight(self, desiredWidth):
return desiredWidth * self.origHeight / self.origWidth
def on_size_allocate(self, obj, rect):
if self.pixbuf is not None:
desiredWidth = min(rect.width-10, self.origWidth)
if self.tempWidth != desiredWidth:
self.tempWidth = desiredWidth
self.tempHeight = self.calculateHeight(desiredWidth)
pixbuf = self.pixbuf.scale_simple(self.tempWidth,
self.tempHeight,
GdkPixbuf.InterpType.BILINEAR)
GLib.idle_add(super(ImageEx, self).set_from_pixbuf,
pixbuf)
我在Gtk.Paned中使用它,它可以正常工作,我可以调整面板和窗口的大小,但是如果我展开窗口我无法使用窗口按钮恢复它但是如果我移动窗口,它恢复正确。
如何存在如此不一致的状态? 我该如何纠正?
谢谢