动态调整图像大小pyGTK(python)

2024-03-28 13:54:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

HelloWorld类中有两个信号:

^{pr2}$

它们在这里:

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

更新 来自this来源: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.。如何写这个容器?在


Tags: andfromimageselfgtkgetfloatwindow
1条回答
网友
1楼 · 发布于 2024-03-28 13:54:55

resize_image()是一个内隐循环。因为如果window接收到check-resize信号,resize_image()就会被调用,图像会被重新呈现,而另一个{}信号会再次发出。。。。在

所以我们需要一些技巧来打破这一点。在

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

相关问题 更多 >