1

我被困在我不明白的问题上。主程序从

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

HelloWorld课堂上我有两个信号:

self.button.connect("file-set", self.load_image)
self.window.connect("check-resize", self.resize_image)

他们在这里:

def load_image(self, widget):
    self.image_loc = self.button.get_filename()
    pixbuf = gtk.gdk.pixbuf_new_from_file(self.image_loc)

    self.resize_image
    print "image loaded"

def resize_image(self, widget):
    allocation = self.scrolledwindow.get_allocation()
    win_h = float(allocation.height)
    win_w = float(allocation.width)
    wk = round(float(win_h / win_w), 6)

    if self.image_loc is not None:
        pixbuf = gtk.gdk.pixbuf_new_from_file(self.image_loc)

        image_h = float(pixbuf.get_height())
        image_w = float(pixbuf.get_width())
        ik = round(float(image_h / image_w), 6)

        if image_h <= win_h and image_w <= win_w:
            pixbuf = pixbuf.scale_simple(int(image_w), int(image_h), gtk.gdk.INTERP_BILINEAR)
        elif (image_h > win_h and image_w <= win_w) or (image_h > win_h and image_w > win_w and ik >= wk):
            pixbuf = pixbuf.scale_simple(int((win_h - 30) * (1 / ik)), int(win_h) - 30, gtk.gdk.INTERP_BILINEAR)
        elif (image_h <= win_h and image_w > win_w) or (image_h > win_h and image_w > win_w and ik < wk):
            pixbuf = pixbuf.scale_simple(int(win_w) - 30, int((win_w - 30) * ik), gtk.gdk.INTERP_BILINEAR)
        else:
            print "WTF? Incorrect image size calculation"
        self.image.set_from_pixbuf(pixbuf)

    print "window resized"

虽然加载图像正常并且调整大小没问题,Ctrl+C但每次调整窗口大小时我都需要。为什么?正如我所发现的,问题是在set_from_pixbuf()方法内部定位的,因为如果我删除它,我会得到“图像加载”和“窗口调整大小”打印而没有循环。追溯:

window resized
window resized
image loaded
window resized
[...lots of prints...]
window resized
^CTraceback (most recent call last):
  File "./photgal.py", line 229, in resize_image
    pixbuf = gtk.gdk.pixbuf_new_from_file(self.image_loc)
KeyboardInterrupt
window resized
[...lots of prints...]
window resized
window resized
^CTraceback (most recent call last):
  File "./photgal.py", line 229, in resize_image
    pixbuf = gtk.gdk.pixbuf_new_from_file(self.image_loc)
KeyboardInterrupt

从此来源更新:据我了解,You can easily get into infinite loops doing this type of thing though.是我的情况,建议The "right way" to调整一个小部件的大小,而另一个小部件已调整大小is usually to write a custom container widget that sizes things the way you want.。这个容器怎么写?

4

1 回答 1

2

resize_image() 是一个无限循环。因为如果window接收到check-resize信号,resize_image()被调用,图像被重新渲染,再次发出另一个check-resize信号......

所以我们需要一些技巧来打破它。

我在这里写了一个小演示应用程序,https://github.com/LiuLang/gtk-test/tree/master/resize-image,它解决了这个问题。

于 2013-06-25T20:51:40.330 回答