虽然我发现这个问题的部分和间接的答案(例如见this link),但我在这里发布这个信息是因为把拼图的零碎拼凑在一起花了我一些时间,而且我认为别人可能会发现我的使用努力。如何使用PyGI在Python3中自动调整图像大小?
那么,如何在父窗口调整大小时实现GTK +按钮上图像的无缝调整大小?
虽然我发现这个问题的部分和间接的答案(例如见this link),但我在这里发布这个信息是因为把拼图的零碎拼凑在一起花了我一些时间,而且我认为别人可能会发现我的使用努力。如何使用PyGI在Python3中自动调整图像大小?
那么,如何在父窗口调整大小时实现GTK +按钮上图像的无缝调整大小?
虽然使用ScrolledWindow代替常用Box的技巧非常有用,但在发布的问题链接中为PyGTK提供的解决方案在GTK3的Python-GI中不起作用。
这是我最小的工作解决方案获取图像的按钮来调整容器的大小。
from gi.repository import Gtk, Gdk, GdkPixbuf
class ButtonWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Button Demo")
self.set_border_width(10)
self.connect("delete-event", Gtk.main_quit)
self.connect("check_resize", self.on_check_resize)
self.box = Gtk.ScrolledWindow()
self.box.set_policy(Gtk.PolicyType.ALWAYS,
Gtk.PolicyType.ALWAYS)
self.add(self.box)
self.click = Gtk.Button()
self.box.add_with_viewport(self.click)
self.pixbuf = GdkPixbuf.Pixbuf().new_from_file('gtk-logo-rgb.jpg')
self.image = Gtk.Image().new_from_pixbuf(self.pixbuf)
self.click.add(self.image)
def resizeImage(self, x, y):
print('Resizing Image to ('+str(x)+','+str(y)+')....')
pixbuf = self.pixbuf.scale_simple(x, y,
GdkPixbuf.InterpType.BILINEAR)
self.image.set_from_pixbuf(pixbuf)
def on_check_resize(self, window):
print("Checking resize....")
boxAllocation = self.box.get_allocation()
self.click.set_allocation(boxAllocation)
self.resizeImage(boxAllocation.width-10,
boxAllocation.height-10)
win = ButtonWindow()
win.show_all()
Gtk.main()
(在宽度和高度的-10是,以适应按钮内边框和填充。我试着用这个摆弄得上的按钮更大的图像,但结果并没有看起来那么好)
本例中使用的jpeg文件可以从here下载。
我欢迎有关如何做到这一点的进一步建议。
self.image = Gtk.Image().new_from_pixbuf(self.pixbuf)
大概应该是: self.image = Gtk.Image().set_from_pixbuf(self.pixbuf)
你正在创建一个新的形象的两倍。
我试着在我的测试程序中更改为这个方法,并获得了回溯(Python 3.2,Debian Wheezy)。可能这种方法对API更新(但文档似乎与此相矛盾)。但是阅读文档我认为你错了两次创建图像(请参见['set_from_pixbuf'](http://www.pygtk.org/pygtk2reference/class-gtkimage.html#method-gtkimage--set-from-pixbuf )和['new_from_pixbuf'](http://www.pygtk.org/pygtk2reference/class-gtkimage.html#function-gtk--image-new-from-pixbuf))。他们都从pixbuf创建一个新的图像。有一个pixbuf,一个图像。 – Bobble