我坚持我不理解的问题。主程序从
运行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
更新
来自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.
。如何写这个容器?</ p>
答案 0 :(得分:2)
resize_image()是一个无限循环。因为如果窗口收到check-resize
信号,则会调用resize_image()
,并重新渲染图像,并再次发出另一个check-resize
信号....
所以我们需要一些技巧来打破这个。
我写了一个小型演示应用程序,https://github.com/LiuLang/gtk-test/tree/master/resize-image,解决了这个问题。